### Eclipse Workspace Patch 1.0
#P contrib
Index: plugins/blocks/quickmail/db/access.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/quickmail/db/access.php,v
retrieving revision 1.2
diff -u -r1.2 access.php
--- plugins/blocks/quickmail/db/access.php	2 Mar 2007 03:06:53 -0000	1.2
+++ plugins/blocks/quickmail/db/access.php	9 Apr 2009 20:42:46 -0000
@@ -1,4 +1,10 @@
 <?php
+/**
+ *   Edited by: Philip Cali
+ *   Date: 2/15/08
+ *   Louisiana State University
+ */
+
 //
 // Capability definitions for the this block.
 //
@@ -44,6 +50,24 @@
             'admin' => CAP_ALLOW
         )
     ),
+
+    'block/quickmail:canconfig' => array (
+    
+            'captype'=>'write',
+                'contextlevel'=> CONTEXT_BLOCK,
+                'legacy'=> array(
+                          'admin'=> CAP_ALLOW
+          )
+    ),
+
+    'block/quickmail:canimpersonate' => array (
+        'captype'=>'read',
+        'contextlevel' => CONTEXT_BLOCK,
+        'legacy'=> array(
+            'admin'=>CAP_ALLOW
+        )
+    )
+    
 );
 
-?>
\ No newline at end of file
+?>
Index: plugins/blocks/quickmail/db/upgrade.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/quickmail/db/upgrade.php,v
retrieving revision 1.2
diff -u -r1.2 upgrade.php
--- plugins/blocks/quickmail/db/upgrade.php	2 Mar 2007 03:06:54 -0000	1.2
+++ plugins/blocks/quickmail/db/upgrade.php	9 Apr 2009 20:42:46 -0000
@@ -1,4 +1,4 @@
-<?php  //$Id: upgrade.php,v 1.2 2007/03/02 03:06:54 mark-nielsen Exp $
+<?php  //$Id: upgrade.php,v 1.1.4.2 2007/03/02 03:01:45 mark-nielsen Exp $
 
 // This file keeps track of upgrades to this block
 //
@@ -17,11 +17,20 @@
 // using the functions defined in lib/ddllib.php
 
 function xmldb_block_quickmail_upgrade($oldversion=0) {
-    $result = true;
+    global $CFG;
 
-    // Nothing for now
+    $result = true;
+    
+/*    //add can:config capability to admin
+    if (!empty($CFG->rolesactive) && $oldversion < 2008021500) { 
+        $admin = get_record('role', 'shortname', 'admin');
+        
+        if (!assign_capability('block/quickmail:canconfig', CAP_ALLOW, $admin->id, 1)){
+            $result = false;
+        }
+    }*/
 
     return $result;
 }
 
-?>
\ No newline at end of file
+?>
Index: plugins/blocks/quickmail/db/mysql.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/quickmail/db/mysql.php,v
retrieving revision 1.3
diff -u -r1.3 mysql.php
--- plugins/blocks/quickmail/db/mysql.php	1 Feb 2006 19:54:59 -0000	1.3
+++ plugins/blocks/quickmail/db/mysql.php	9 Apr 2009 20:42:46 -0000
@@ -1,4 +1,9 @@
 <?PHP  //$Id: mysql.php,v 1.3 2006/02/01 19:54:59 michaelpenne Exp $
+/*
+    Edited by: Philip Cali
+    Date: 2/15/08
+    Louisiana State University
+*/
 //
 // This file keeps track of upgrades to Moodle's
 // blocks system.
@@ -24,7 +29,7 @@
     
     $result = true;
     
-    if ($oldversion < 2005012800 && $result) {
+    if ($oldversion < 2008021500 && $result) {
         execute_sql(" create table ".$CFG->prefix."block_quickmail_log
                     ( id int(10) unsigned not null auto_increment,
                       courseid int(10) unsigned not null,
Index: plugins/blocks/quickmail/block_quickmail.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/quickmail/block_quickmail.php,v
retrieving revision 1.10
diff -u -r1.10 block_quickmail.php
--- plugins/blocks/quickmail/block_quickmail.php	2 Mar 2007 03:06:53 -0000	1.10
+++ plugins/blocks/quickmail/block_quickmail.php	9 Apr 2009 20:42:46 -0000
@@ -1,14 +1,18 @@
-<?php // $Id: block_quickmail.php,v 1.10 2007/03/02 03:06:53 mark-nielsen Exp $
+<?php // $Id: block_quickmail.php,v 2.5 2008/02/15 09:53:43 pcali1 Exp $
+
+/**
+    Edited by: Philip Cali
+    Date: 2/15/2008
+    Louisiana State University
+**/
+
 /**
  * Quickmail - Allows teachers and students to email one another
- *      at a course level.  Also supports group mode so students
- *      can only email their group members if desired.  Both group
- *      mode and student access to Quickmail are configurable by
- *      editing a Quickmail instance.
+ *      at a course level. This version of Quickmail disabled the group
+ *      mode as it is still not stable in Moodle 1.8
  *
- * @author Mark Nielsen
- * @version $Id: block_quickmail.php,v 1.10 2007/03/02 03:06:53 mark-nielsen Exp $
- * @package quickmail
+ * @Original author Mark Nielsen, updated by Bibek Bhattarai and Wen Hao Chuang
+ * @package quickmailv2
  **/ 
 
 /**
@@ -16,115 +20,207 @@
  * functions for a Moodle block.  Has some extra functions as well
  * to increase its flexibility and useability
  *
- * @package quickmail
- * @todo Make a global config so that admins can set the defaults (default for student (yes/no) default for groupmode (select a groupmode or use the courses groupmode)) NOTE: make sure email.php and emaillog.php use the global config settings
+ * @package moodleblock
+ * @author Mark Nielsen
+ * @todo Make a global config so that admins can set the defaults (default for student (yes/no) default for groupmode (select a groupmode or use the courses groupmode)) 
+ * NOTE: make sure email.php and emaillog.php use the global config settings
  **/
-class block_quickmail extends block_list {
-    
+class block_quickmail extends block_list {    
+
     /**
      * Sets the block name and version number
      *
      * @return void
+     * @author Mark Nielsen
      **/
     function init() {
-        $this->title = get_string('blockname', 'block_quickmail');
-        $this->version = 2006021501;  // YYYYMMDDXX
+        $this->title = get_string('blockname', 'block_quickmail'). ' v2.5';
+		//$this->title = this->title.' Beta Test Version';
+        $this->version = 2008021500;  // YYYYMMDDXX
     }
     
     /**
+     * Limits where the block can be added.
+     **/
+    function applicable_formats() {
+        return array('site' => false, 'my' => false, 'course' => true);
+    }
+
+    /**
      * Gets the contents of the block (course view)
      *
      * @return object An object with an array of items, an array of icons, and a string for the footer
+     * @author Mark Nielsen
      **/
     function get_content() {
-        global $USER, $CFG;
+        global $USER, $CFG, $COURSE;
 
         if($this->content !== NULL) {
             return $this->content;
         }
-
+        
         $this->content = new stdClass;
         $this->content->footer = '';
         $this->content->items = array();
         $this->content->icons = array();
         
-        if (empty($this->instance) or !$this->check_permission()) {
+        if (empty($this->instance)) {
             return $this->content;
         }
 
-    /// link to composing an email
-        $this->content->items[] = "<a href=\"$CFG->wwwroot/blocks/quickmail/email.php?id={$this->course->id}&amp;instanceid={$this->instance->id}\">".
-                                    get_string('compose', 'block_quickmail').'</a>';
+    /// load defaults (will only load if config is empty)
+        $this->load_defaults();
 
+        $this->load_course();
+        
+        if ($this->check_permission('block/quickmail:cansend', CONTEXT_COURSE, $COURSE) || $this->allow_students_to_email($USER->id)) {
+                
+    /// link to composing an email
+    /// here we revised a little bit to add a question mark for HELP button - Wen Hao Chuang
         $this->content->icons[] = '<img src="'.$CFG->pixpath.'/i/email.gif" height="16" width="16" alt="'.get_string('email').'" />';
+        $this->content->items[] = '<a href="'.$CFG->wwwroot.'/blocks/quickmail/email.php?id='.$this->course->id.'&instanceid='.$this->instance->id.'">'.
+                                    get_string('composeemail', 'block_quickmail').'</a>'.'	<a target="popup" title="Quickmail" href="../help.php?module=moodle&file=quickmail.html" onclick="return openpopup(\'/help.php?module=moodle&file=quickmail.html\', \'popup\', \'menubar=0,location=0,scrollbars,resizable,width=500,height=400\', 0);"><img height="17" width="17" alt="quickmail" src="../pix/help.gif" /></a>';
 
-    /// link to history log
-        $this->content->items[] = "<a href=\"$CFG->wwwroot/blocks/quickmail/emaillog.php?id={$this->course->id}&amp;instanceid={$this->instance->id}\">".
-                                    get_string('history', 'block_quickmail').'</a>';
+        
 
+        if ($this->check_permission('block/quickmail:cansend', CONTEXT_COURSE, $COURSE)) {
+    /// link to history log
         $this->content->icons[] = '<img src="'.$CFG->pixpath.'/t/log.gif" height="14" width="14" alt="'.get_string('log').'" />';
+       $this->content->items[] = '<a href="'.$CFG->wwwroot.'/blocks/quickmail/emaillog.php?id='.$this->course->id.'&instanceid='.$this->instance->id.'">'.
+                                   get_string('emailhistory', 'block_quickmail').'</a>';
+
+        }
+    
+        }
 
+    /// link to config for teachers
+        if ($this->check_permission('block/quickmail:canconfig', CONTEXT_COURSE, $COURSE)) {
+            //$this->content->footer = "<a href=\"$CFG->wwwroot/course/view.php?id={$this->instance->pageid}&instanceid={$this->instance->id}&sesskey=$USER->sesskey&blockaction=config\">".
+              $this->content->footer = '<a href="'. $CFG->wwwroot.'/blocks/quickmail/quickmail_config.php?id='.$this->course->id.'&instanceid='.$this->instance->id.'">'.
+              get_string('settings').'...</a>';
+        }
+        
         return $this->content;
     }
-
+    
     /**
-     * Loads the course
+     * Allows the block to be configurable at an instance level.
      *
-     * @return void
+     * @return boolean
+     * @author Mark Nielsen
      **/
-    function specialization() {
-        global $COURSE;
-
-        $this->course = $COURSE;
+    function instance_allow_config() {
+        return false;
     }
-
+   
     /**
-     * Cleanup the history
+     * New validation method checks by role capability
      *
-     * @return boolean
-     **/
-    function instance_delete() {
-        return delete_records('block_quickmail_log', 'courseid', $this->course->id);
+     */
+    function check_permission($action, $context_constant, $course) {
+        switch ($context_constant) {
+            case CONTEXT_COURSE:
+                $context = get_context_instance ($context_constant, $course->id);
+                break;
+            case CONTEXT_BLOCK:
+                $context = get_context_instance ($context_constant, $this->instance->id);
+            default:
+                return false;
+        }
+        return has_capability($action, $context);
     }
 
     /**
-     * Set defaults for new instances
+     * Special validation method for allowing student to use quickmail
      *
-     * @return boolean
-     **/
-    function instance_create() {
-        $this->config = new stdClass;
-        $this->config->groupmode = $this->course->groupmode;
-        $pinned = (!isset($this->instance->pageid));
-        return $this->instance_config_commit($pinned);
-    }
+     */
+    function allow_students_to_email($userid) {
+        global $CFG;
+
+        if (!$this->config->allowstudents) {
+            return false;
+        }
 
+        $sql = "SELECT COUNT(*)
+                 FROM {$CFG->prefix}role_assignments ra,
+                      {$CFG->prefix}role r
+                 WHERE r.id = ra.roleid
+                   AND r.shortname = 'student'
+                   AND ra.userid = {$userid}";
+        
+        return (count_records_sql($sql) ? true : false);
+    }
+ 
     /**
-     * Allows the block to be configurable at an instance level.
+     * Get the groupmode of Quickmail.  This function pays
+     * attention to the course group mode force.
      *
-     * @return boolean
+     * @return int The group mode of the block
+     * @author Mark Nielsen
      **/
-    function instance_allow_config() {
-        return true;
+    function groupmode() {
+        $this->load_course();
+                
+        if ($this->course->groupmodeforce) {
+            return $this->course->groupmode;
+        } else {
+            return $this->config->groupmode;
+        }
     }
 
+ 
     /**
-     * Check to make sure that the current user is allowed to use Quickmail.
+     * Loads default config data when config is empty (that way we know it exists).
      *
-     * @return boolean True for access / False for denied
+     * Defaults:
+     *      group mode           = course group mode
+     *      allow student access = yes
+     * @return void
+     * @author Mark Nielsen
+     * @todo Make a global config so that admins can set the defaults (default for student (yes/no) default for groupmode (select a groupmode or use the courses groupmode))  NOTE: make sure email.php and emaillog.php use the global config settings
      **/
-    function check_permission() {
-        return has_capability('block/quickmail:cansend', get_context_instance(CONTEXT_BLOCK, $this->instance->id));
+    function load_defaults() {
+        if (empty($this->config)) {
+        /// blank config
+            global $CFG;
+            $this->load_course();
+
+            $defaults = new stdClass;
+            $defaults->groupmode = $this->course->groupmode;
+            $defaults->allowstudents = 0;
+
+            //Student is a default role selection
+            $student = get_record('role', 'shortname', 'student');
+            
+            $defaults->roleselection[$student->shortname] = $student->name;
+
+            $this->instance_config_save($defaults);
+        }
     }
+    
+    /**
+        Convenience method to retrieve the configured role selections
+    */
+    function grab_roles() {
+        return $this->config->roleselection;
+    }
+
 
     /**
-     * Get the groupmode of Quickmail.  This function pays
-     * attention to the course group mode force.
+     * Loads the course record into $this->course.
      *
-     * @return int The group mode of the block
+     * This function first checks to make sure that
+     * the course is not already loaded first.  If not,
+     * then grab it from the database
+     *
+     * @return void
+     * @author Mark Nielsen
      **/
-    function groupmode() {
-        return groupmode($this->course, $this->config);
+    function load_course() {
+        if (empty($this->course)) {
+            $this->course = get_record('course', 'id', $this->instance->pageid);
+        }
     }
 }
+
 ?>
Index: plugins/blocks/quickmail/styles.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/quickmail/styles.php,v
retrieving revision 1.4
diff -u -r1.4 styles.php
--- plugins/blocks/quickmail/styles.php	2 Mar 2007 03:06:53 -0000	1.4
+++ plugins/blocks/quickmail/styles.php	9 Apr 2009 20:42:46 -0000
@@ -1,5 +1,5 @@
 /***
-*** General Table Styles
+    General Table Styles
 ***/
 
 .blocks-quickmail .generaltable .r0 {
@@ -11,27 +11,29 @@
 }
 
 /***
-*** Flexible Table Styles (emaillog.php)
+    Flexible Table Styles (emaillog.php)
 ***/
 
 body#blocks-quickmail-emaillog table#emaillog .header {
-    text-align: left;
+  text-align: left;
 }
 
 body#blocks-quickmail-emaillog table#emaillog .header .commands {
     display: inline;
 }
 
-body#blocks-quickmail-emaillog table#emaillog td  {
-    border-left-width: 1px;
-    border-right-width: 1px;
-    border-left-style: solid;
-    border-right-style: solid;
-    vertical-align: bottom;
-    border-color: #DDDDDD;
+body#blocks-quickmail-emaillog table#emaillog td 
+{
+  border-left-width: 1px;
+  border-right-width: 1px;
+  border-left-style: solid;
+  border-right-style: solid;
+  vertical-align: bottom;
+  border-color: #DDDDDD;
 }
 
 body#blocks-quickmail-emaillog table#emaillog .header,
-body#blocks-quickmail-emaillog table#emaillog .cell {
-    padding: 4px;
+body#blocks-quickmail-emaillog table#emaillog .cell
+{
+  padding: 4px;
 }
\ No newline at end of file
Index: plugins/blocks/quickmail/emaillog.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/quickmail/emaillog.php,v
retrieving revision 1.14
diff -u -r1.14 emaillog.php
--- plugins/blocks/quickmail/emaillog.php	30 Aug 2007 17:33:48 -0000	1.14
+++ plugins/blocks/quickmail/emaillog.php	9 Apr 2009 20:42:46 -0000
@@ -1,54 +1,67 @@
-<?php // $Id: emaillog.php,v 1.14 2007/08/30 17:33:48 mark-nielsen Exp $
-/**
- * emaillog.php - displays a log (or history) of all emails sent by
- *      a specific in a specific course.  Each email log can be viewed
- *      or deleted.
- *
- * @todo Add a print option?
- * @author Mark Nielsen
- * @version $Id: emaillog.php,v 1.14 2007/08/30 17:33:48 mark-nielsen Exp $
- * @package quickmail
- **/
+<?php // $Id: emaillog.php,v 2.5 2008/02/15 16:39:18 pcali1 Exp $
     
+    /**
+     *  Edited by: Philip Cali
+     *  Date: 2/15/2008
+     *  Louisiana State University
+     *
+     *  Updated permissions
+     */
+    /**
+     * emaillog.php - displays a log (or history) of all emails sent by
+     *      a specific in a specific course.  Each email log can be viewed
+     *      or deleted.
+     * For our quickmail version we are not using this file at all. 
+     * We only included it here for reference
+     * @todo Add a print option?
+     * @author Mark Nielsen
+     * @version $Id: emaillog.php,v 1.11 2006/04/05 16:39:18 michaelpenne Exp $
+     * @package quickmail
+     **/    
+
     require_once('../../config.php');
-    require_once($CFG->libdir.'/blocklib.php');
+    require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
     require_once($CFG->libdir.'/tablelib.php');
+    require_once('block_quickmail.php');
     
+    require_login();
+
     $id = required_param('id', PARAM_INT);    // course id
     $action = optional_param('action', '', PARAM_ALPHA);
     $instanceid = optional_param('instanceid', 0, PARAM_INT);
 
-    $instance = new stdClass;
-
-    if (!$course = get_record('course', 'id', $id)) {
+    $quickmail = new block_quickmail();
+    $instance = new stdClass;    
+    
+    if (! $course = get_record('course', 'id', $id)) {
         error('Course ID was incorrect');
     }
 
-    require_login($course->id);
-
-    if ($instanceid) {
-        $instance = get_record('block_instance', 'id', $instanceid);
-    } else {
-        if ($quickmailblock = get_record('block', 'name', 'quickmail')) {
-            $instance = get_record('block_instance', 'blockid', $quickmailblock->id, 'pageid', $course->id);
+      $quickmailresult = get_record('block', 'name', 'quickmail');
+      if ($instanceid && $quickmailresult) {
+        $instance = get_record('block_instance', 'id', $instanceid, 'blockid', $quickmailresult->id);
+        if (!$instance){
+            $instance = get_record('block_pinned', 'id', $instanceid, 'blockid', $quickmailresult->id);
         }
-    }
+     }    
 
 /// This block of code ensures that Quickmail will run 
 ///     whether it is in the course or not
     if (empty($instance)) {
-        if (has_capability('block/quickmail:cansend', get_context_instance(CONTEXT_BLOCK, $instanceid))) {
-            $haspermission = true;
-        } else {
+        if (isGuest()) {
             $haspermission = false;
+        } else {
+            $haspermission = true;
         }
     } else {
         // create a quickmail block instance
-        $quickmail = block_instance('quickmail', $instance);
-        $haspermission = $quickmail->check_permission();
+        $quickmail->_load_instance($instance);
+        $quickmail->load_defaults();
+        
+        $haspermission = $quickmail->check_permission('block/quickmail:cansend', CONTEXT_COURSE, $course);
     }
     
-    if (!$haspermission) {
+    if (!$haspermission && !is_siteadmin($USER->id)) {
         error('Sorry, you do not have the correct permissions to use Quickmail.');
     }
     
@@ -75,7 +88,7 @@
 /// define table columns, headers, and base url
     $table->define_columns($tablecolumns);
     $table->define_headers($tableheaders);
-    $table->define_baseurl($CFG->wwwroot.'/blocks/quickmail/emaillog.php?id='.$course->id.'&amp;instanceid='.$instanceid);
+    $table->define_baseurl($CFG->wwwroot.'/blocks/quickmail/emaillog.php?id='.$course->id.'&amp;instanceid='.$instance->id);
 
 /// table settings
     $table->sortable(true, 'timesent', SORT_DESC);
@@ -97,80 +110,82 @@
     $table->setup();  
     
 /// SQL
-    $sql = "SELECT * 
-              FROM {$CFG->prefix}block_quickmail_log
-             WHERE courseid = $course->id 
-               AND userid = $USER->id ";
+    $selectfrom = "SELECT * FROM {$CFG->prefix}block_quickmail_log ";
+    $where = "WHERE courseid = $course->id AND userid = $USER->id ";
 
-    if ($table->get_sql_where()) {
-        $sql .= 'AND '.$table->get_sql_where();
+    if($table->get_sql_where()) {
+        $where .= 'AND '.$table->get_sql_where();
     }
 
-    $sql .= ' ORDER BY '. $table->get_sql_sort();
-
+    $sort = ' ORDER BY '. $table->get_sql_sort();
+           
 /// set page size
     $total = count_records('block_quickmail_log', 'courseid', $course->id, 'userid', $USER->id);
     $table->pagesize(10, $total);
 
-    if ($pastemails = get_records_sql($sql, $table->get_page_start(), $table->get_page_size())) {
+    if($table->get_page_start() !== '' && $table->get_page_size() !== '') {
+        $limitfrom = $table->get_page_start();
+	$limitnum =  $table->get_page_size();
+    } else {
+        $limit = '';
+    }
+
+    if ($pastemails = get_records_sql($selectfrom.$where.$sort,$limitfrom,$limitnum)) {
+        
         foreach ($pastemails as $pastemail) {
             $table->add_data( array(userdate($pastemail->timesent),
-                                    s($pastemail->subject),
-                                    format_string($pastemail->attachment, true),
-                                    "<a href=\"email.php?id=$course->id&amp;instanceid=$instanceid&amp;emailid=$pastemail->id&amp;action=view\">".
-                                    "<img src=\"$CFG->pixpath/i/search.gif\" height=\"14\" width=\"14\" alt=\"".get_string('view').'" /></a> '.
-                                    "<a href=\"emaillog.php?id=$course->id&amp;instanceid=$instanceid&amp;sesskey=$USER->sesskey&amp;action=dump&amp;emailid=$pastemail->id\">".
-                                    "<img src=\"$CFG->pixpath/t/delete.gif\" height=\"11\" width=\"11\" alt=\"".get_string('delete').'" /></a>'));
+                                   $pastemail->subject,
+                                   $pastemail->attachment,
+                                   "<a href=\"email.php?id=$course->id&amp;instanceid=$instance->id&amp;emailid=$pastemail->id&amp;action=view\">".
+                                   "<img src=\"$CFG->pixpath/i/search.gif\" height=\"14\" width=\"14\" alt=\"".get_string('view').'" /></a> '.
+                                   "<a href=\"emaillog.php?id=$course->id&amp;instanceid=$instance->id&amp;sesskey=$USER->sesskey&amp;action=dump&amp;emailid=$pastemail->id\">".
+                                   "<img src=\"$CFG->pixpath/t/delete.gif\" height=\"11\" width=\"11\" alt=\"".get_string('delete').'" /></a>'
+                                   )
+                             );
         }
     }
     
 /// Start printing everyting
-    $strquickmail = get_string('blockname', 'block_quickmail');
-    if (empty($pastemails)) {
-        $disabled = 'disabled="disabled" ';
-    } else {
-        $disabled = '';
-    }
-    $button = "<form method=\"post\" action=\"$CFG->wwwroot/blocks/quickmail/emaillog.php\">
-               <input type=\"hidden\" name=\"id\" value=\"$course->id\" />
-               <input type=\"hidden\" name=\"instanceid\" value=\"$instanceid\" />
-               <input type=\"hidden\" name=\"sesskey\" value=\"".sesskey().'" />
-               <input type="hidden" name="action" value="confirm" />
-               <input type="submit" name="submit" value="'.get_string('clearhistory', 'block_quickmail')."\" $disabled/>
-               </form>";
-    
-/// Header setup
-    if ($course->category) {
-        $navigation = "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->";
-    } else {
-        $navigation = '';
-    }
+    $stremailhistory = get_string('emailhistory', 'block_quickmail');
+    $strquickmail    = get_string('blockname', 'block_quickmail');
 
-    print_header("$course->fullname: $strquickmail", $course->fullname, "$navigation $strquickmail", '', '', true, $button);
 
-    print_heading($strquickmail);
-    
-    $currenttab = 'history';
-    include($CFG->dirroot.'/blocks/quickmail/tabs.php');
+    $navigation = array(
+                array('name' => $course->shortname, 'link' => "{$CFG->wwwroot}/course/view.php?id=$course->id", 'type'=> 'title'),
+                array('name' => $strquickmail, 'link'=>'', 'type'=>'title'),
+                );
+
+    print_header_simple($strquickmail, '', build_navigation($navigation));
+
+
+
+/*    print_header($course->fullname.': '.$stremailhistory, $course->fullname, "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">".
+                 "$course->shortname</a> -> <a href=\"email.php?id=$course->id&amp;instanceid=$instance->id\">$strquickmail</a> -> $stremailhistory",
+                 '', '', true);
+*/
+    print_heading($stremailhistory);
     
 /// delete reporting happens here
     if ($action == 'dump') {
         if ($dumpresult) {
-            notify(get_string('deletesuccess', 'block_quickmail'), 'notifysuccess');
+            notify(get_string('deletesuccess', 'block_quickmail'));
         } else {
             notify(get_string('deletefail', 'block_quickmail'));
         }
     }
-
-    if ($action == 'confirm') {
-        notice_yesno(get_string('areyousure', 'block_quickmail'), 
-                     "$CFG->wwwroot/blocks/quickmail/emaillog.php?id=$course->id&amp;instanceid=$instanceid&amp;sesskey=".sesskey()."&amp;action=dump",
-                     "$CFG->wwwroot/blocks/quickmail/emaillog.php?id=$course->id&amp;instanceid=$instanceid");
-    } else {
-        echo '<div id="tablecontainer">';
-        $table->print_html();
-        echo '</div>';
+    
+/// print table
+    echo '<div id="tablecontainer">';
+    $table->print_html();
+    echo '</div>';
+    
+/// links to compose new email or to delete the history log
+    echo '<p align="center">'.
+         "<a href=\"email.php?id=$course->id&amp;instanceid=$instance->id\">".get_string("composenew", "block_quickmail").'</a> ';
+    if (isset($pastemails) and !empty($pastemails)) {
+        echo "| <a href=\"emaillog.php?id=$course->id&amp;instanceid=$instance->id&amp;sesskey=".$USER->sesskey."&amp;action=dump\">".get_string('clearhistory', 'block_quickmail').'</a>';
     }
+    echo '</p>';
 
-    print_footer();
-?>
\ No newline at end of file
+    print_footer();              
+?>
Index: plugins/blocks/quickmail/email.html
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/quickmail/email.html,v
retrieving revision 1.13
diff -u -r1.13 email.html
--- plugins/blocks/quickmail/email.html	2 Mar 2007 03:06:53 -0000	1.13
+++ plugins/blocks/quickmail/email.html	9 Apr 2009 20:42:46 -0000
@@ -1,98 +1,312 @@
-<?php // $Id: email.html,v 1.13 2007/03/02 03:06:53 mark-nielsen Exp $
-/**
- * email.html - Prints the email form for Quickmail
- *
- * @author Mark Nielsen
- * @version $Id: email.html,v 1.13 2007/03/02 03:06:53 mark-nielsen Exp $
- * @package quickmail
- **/
-?>
-
-<form name="theform" method="post" action="email.php" enctype="multipart/form-data">
-<table border="0" cellpadding="5">
-<tr valign="top">
-    <td align="right"><strong><?php print_string('to', 'block_quickmail'); ?>:</strong></td>
-    <td>
-        <a href="javascript:void(0);" onclick="block_quickmail_toggle(true, 1, 0);"><?php print_string('selectall'); ?></a> / <a href="javascript:void(0);" onclick="block_quickmail_toggle(false, 1, 0);"><?php print_string('deselectall'); ?></a>
-        <br />
-        <br />
-        <?php print_table($table); ?>
-    </td>
-</tr>
-<tr valign="top">
-    <td align="right"><b><?php print_string('subject', 'forum'); ?>:</b></td>
-    <td>
-        <input type="text" name="subject" size="60" value="<?php p($form->subject); ?>" />
-    </td>
-</tr>
-<tr valign="top">
-    <td align="right"><b>
-     <?php print_string('message', 'forum'); ?>:
-     </b></td>
-    <td align="left" rowspan="2">
-    <?php print_textarea($usehtmleditor, 25, 65, 630, 400, 'message', $form->message); ?>
-    </td>
-</tr>
-<tr valign="top">
-    <td align="right" valign="center" nowrap="nowrap">
-        <font size="2">
-            <?php
-                helpbutton('reading', get_string('helpreading'), 'moodle', true, true);
-                echo '<br />';
-                helpbutton('writing', get_string('helpwriting'), 'moodle', true, true);
-                echo '<br />';
-                if ($usehtmleditor) {
-                   helpbutton('richtext', get_string('helprichtext'), 'moodle', true, true);
-                } else {
-                   emoticonhelpbutton('theform', 'message');
-                } 
-            ?>
-         </font>
-    </td>
-</tr>
-
-<tr valign="top">
-    <td align="right"><b><?php print_string('formattexttype'); ?>:</b></td>
-    <td>
-    <?php 
-        if ($usehtmleditor) {   /// Trying this out for a while
-            print_string('formathtml');
-            echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
-        } else {
-            choose_from_menu(format_text_menu(), 'format', $form->format, '');
-        }
-        helpbutton('textformat', get_string('helpformatting'));
-     ?>
-    </td>
-</tr>
-
-<tr valign="top">
-    <td align="right" nowrap="nowrap">
-        <b><?php print_string('attachmentoptional', 'block_quickmail'); ?>:</b>
-    </td>
-    <td>
-    <?php
-        if (has_capability('moodle/course:managefiles', $context)) {
-            echo '<input type="text" name="attachment" size="90" value="'.$form->attachment.'" alt="'.get_string('attachmentalt', 'block_quickmail').'" /><br />';
-            button_to_popup_window ("/files/index.php?id=$course->id&choose=theform.attachment", "coursefiles", $strchooseafile, 500, 750, $strchooseafile);
-        } else {
-            $maxbytes = get_max_upload_file_size($CFG->maxbytes, $course->maxbytes);
-            echo '<input type="hidden" name="MAX_FILE_SIZE" value="'.$maxbytes.'" />';
-            echo '<input type="file" name="attachment" size="45" alt="'.get_string('attachmentalt', 'block_quickmail').'" /> ';
-            print_string('maxsize', '', display_size($maxbytes));
-        }
-    ?>
-    </td>
-</tr>
-
-<tr>
-    <td align="center" colspan="2">
-    <input type="hidden" name="sesskey" value="<?php echo sesskey(); ?>" />
-    <input type="hidden" name="id" value="<?php echo $course->id; ?>" />
-    <input type="hidden" name="instanceid" value="<?php echo $instanceid; ?>" />
-    <input type="submit" name="cancel" value="<?php print_string('cancel') ?>" />
-    <input type="submit" name="sendemail" value="<?php print_string('sendemail', 'block_quickmail') ?>" />
-    </td>
-</tr>
-</table>
-</form>
+<?php // $Id: email.html,v 2.5 2008/02/15 09:53:43 pcali1 Exp $
+
+/**
+ * email.html - Prints the email form for Quickmail
+ *
+ * @Original author Mark Nielsen, updated by Bibek Bhattarai and Wen Hao Chuang
+ * @version $Id: email.html,v 2.01 2007/04/05 09:33:43 wenhaochuang Exp $
+ * @package quickmailv2 (enhanced quickmail for large classes)
+ **/
+ 
+/**
+ * Updated features:
+ *	- Replaces checkbox with selection list for effective usability in case of larger classes
+ *  - Added external email client feature
+ *  - Added a help button to explain external email client
+ *  - Removed group mode functionality
+ *  - Removed email log on the server side. We allow users to use external email client so that they could keep a record
+ *  - but we do not want all these logs exhaust our precious server space as we have many quickmail users
+ **/ 
+
+/**
+ *   Edited by: Philip Cali
+ *   Date: 2/15/2008
+ *   Louisiana State University
+ *   
+ *   - Added role filters and group selections
+ *   - Can send email with no message text
+ *   - Can add multiple attachments
+ *   - Can choose whether or not to receive receipts
+ **/
+
+?>
+<!-- link to javascript in selection.js -->
+<script language="JavaScript" src="selection.js"></script>
+<script language="Javascript" src="attachment.js"></script>
+<!-- calls function java script createListObjects every time theform is loaded -->
+
+<!-- Call java script function createListObject every time the form is re-loaded !-->
+<form name="theform" method="post" action="email.php" enctype="multipart/form-data">
+<table border="0" cellpadding="5" id="maintable">
+<tr>
+  <td colspan="2" align="right">
+    <?php
+        if ($quickmail->check_permission('block/quickmail:cansend', CONTEXT_COURSE, $course)) {
+        echo '<a href="emaillog.php?id='. $course->id . '&amp;instanceid='. $instance->id.'">'. get_string('emailhistory', 'block_quickmail'). '</a>';
+        }    
+  ?>
+  </td>
+</tr>
+<tr>
+  <td align="right"><b>From:</b></td>
+  <td align="left"><?php echo $USER->email; ?></td>
+</tr>
+<tr valign="top">
+    <tr><td align="right" width="200"></td></tr>
+    <td align="right"><div align="center"></div></td>
+    
+    <td width = "200">
+    <table width="200"><tr><td align="left" width="200"><div align="right"><strong><?php print_string('to', 'block_quickmail'); ?></strong></div></td></tr>
+    <tr>
+    <td width="250">
+        <div align="left">
+          <!-- Populate mailto list from $mail_list that stored list of users to be emailed variable -->
+		  <select name="mail_to" size="31" multiple id="mail_to" style="width:250px">
+			<?php
+				foreach($mail_list as $id) { 
+          			$id = stripslashes($id);
+					$id = str_replace("\"","",$id);
+					if($id != ""){
+                     $mail_groups = array();
+                     $mail_groups = $groupmembers_to_groupid[$id];
+                     if (!$mail_groups){
+                         $mail_group = new stdClass();
+                         $mail_group->id = 0;
+                         $mail_group->name = get_string('nosection', 'block_quickmail');
+                         $mail_groups[] = $group;
+                     }
+                     $groupsid = '';
+                     $groups_name = '';
+                     foreach ($mail_groups as $group) {
+                         $groupsid .= '' . $group->id . ',';
+                         $groups_name .= '' . $group->name . ',';
+                     }
+                     
+                    $user_roles = '';
+                    foreach ($roles_to_userid[$user->id] as $role) {
+                        $user_roles .= $role->shortname . ',';
+                    }
+ 
+                     echo '<option value="'.$id.' '. $courseusers[$id]->email.' '. $groupsid . ' '.'' .'">'.
+                             fullname($courseusers[$id], true).' ('. trim($groups_name, ",").')</option>';
+
+					}
+          		}				
+       		?>
+		</select>
+        </div></td>
+        </tr></table></td>
+    <td width="75">
+		<div align="center" margin-top="10px">
+          	<p><input type = "button" id="add" onClick="add_user()" style="width:100px;" value="<?php echo $THEME->larrow?> Add" title="Add selected user to selected recipients list" />
+          	</p>
+          	<p><input type = "button" id="remove" onClick="remove_user()" style="width:100px;" value="Remove <?php echo $THEME->rarrow?>" title="Remove selected users from selected recipients list"/>
+          	</p>
+          	<p><input type = "button" id="addall" onClick="addAll()" style="width:100px;" value="Add all" title="Add all users from selected recipients list"/></p>
+          	<p><input type = "button" id="removeall" onClick="removeAll()" style="width:100px;" value="Remove all" title="Add all users from selected recipients list"/></p>          	
+		</div></td>
+    <td width="300">
+    <table width="250">
+    
+    <!-- Creates sections for role selection-->
+    <tr><td align="right" width="250"><div align="right"><strong><?php print_string('rolefilter', 'block_quickmail'); ?></strong></div></td></tr>
+    <tr>
+        <td width="250"><div align="right">
+            <select id="roles" onchange="special_select_users()" style="width:250px">
+            <?php
+                $no_filter = get_string('no_filter', 'block_quickmail');
+                echo "<option value=\"none\" selected=\"selected\">$no_filter</option>";
+                foreach($quickmail->grab_roles() as $role_shortname => $role_name) {
+                    echo '<option value="'. $role_shortname .'">'.$role_name.'s only</option>';
+                }
+            ?>
+            </select></div>
+        </td>
+    </tr>
+
+    <tr><td align="right" width="250"><div align="right"><strong><?php print_string('potentialgroups', 'block_quickmail'); ?></strong></div></td></tr>
+<tr>
+<td width="250"><div align="right">
+<!-- Populate members list from $groups that stores list of groups in the course -->
+      
+    
+      <select name="groups" size="5" multiple id="groups" onchange="special_select_users()" style="width:250px">
+       <?php
+         foreach($groups as $group) { 
+                    echo '<option value="'.$group->id.' group">'. $group->name .'</option>';
+         }
+         //Have this option for those courses with a ton of people not in sections
+         echo '<option value="0 group">'. get_string('nosection', 'block_quickmail') .'</option>'
+     ?>       
+      </select>
+
+    </div></td></tr>
+     <tr><td align="right" width="250"><div align="right"><strong><?php print_string('potentialreceipent', 'block_quickmail'); ?></strong></div></td></tr>
+    <tr><td width="250"><div align="right">
+  
+      <!-- Populate members list from $courseusers that stores list of users in the course -->		  
+	  <select name="members" size="20" multiple id="members" style="width:250px">
+      <?php
+		foreach($courseusers as $user) { 
+			$show = true;
+			//if the id already exists in mail_list id then do not display
+			foreach($mail_list as $id){
+				$id = stripslashes($id);
+				$id = str_replace("\"","",$id);
+				if($id == $user->id){
+					$show = false;
+				}						
+			}
+			if($show){
+                    $groups = array();
+                    $groups = $groupmembers_to_groupid[$user->id];
+                    if (!$groups){
+                        $group = new stdClass();
+                        $group->id = 0;
+                        $group->name = get_string('nosection', 'block_quickmail');
+                        $groups[] = $group;
+                    }
+                    $groupsid = '';
+                    $groups_name = '';
+                    foreach ($groups as $group) {
+                        $groupsid .= '' . $group->id . ',';
+                        $groups_name .= '' . $group->name . ',';
+                    }                     
+
+                    $user_roles = '';
+                    foreach ($roles_to_userid[$user->id] as $role) {
+                        $user_roles .= $role->shortname . ',';
+                    }
+                    
+                    echo '<option value="'.$user->id.' '.$user->email.' '. $groupsid . ' '. $user_roles .'">'. 
+                            fullname($user, true).' ('. trim($groups_name, ",").')</option>';
+                }
+		    }
+      ?>          
+	  </select>
+    </div></td></tr></table></td>
+</tr>
+<!--<tr valign="top">
+  <td align="right"></td>
+  <td colspan="3">
+  	<input type = "button" id="mailto" onClick="mail_to_ext_client()" value="Use external email client to send this message"/>
+  <?php
+      helpbutton('extemail', 'moodle', true, true);
+      echo '<br />';
+  ?>
+  </td>
+</tr>
+-->
+
+
+<tr>
+    <td align="right" nowrap="nowrap">
+        <strong><?php print_string('attachmentoptional', 'block_quickmail'); ?>(s):</strong>
+    </td>
+</tr>
+
+<tr valign="top" id="attach_1row">
+    <td align="right" nowrap="nowrap">
+    </td>
+    <td colspan="2">
+    <?php
+            $maxbytes = get_max_upload_file_size($CFG->maxbytes, $course->maxbytes);
+            echo '<input type="hidden" name="MAX_FILE_SIZE" value="'.$maxbytes.'" />';
+            echo '<input id="attach_1" type="file" name="attach_1" size="45" alt="'.get_string('attachmentalt', 'block_quickmail').'" onchange="javascript:create_new_attachment(\'attach_1\')"/> ';
+        //}
+    ?>
+    </td>
+</tr>
+
+<tr>
+    <td></td>
+    <td colspan="2">
+        <?php
+            echo '<b><font color= color= color="#000000">';
+			print_string('maxattachmentsize', 'block_quickmail'); echo ': 10MB'; //display_size($maxbytes);
+			echo'<br>';
+			//print_string('useextclient','block_quickmail');
+			echo '</b></font>';
+        ?>
+    </td>
+</tr>
+
+<tr valign="top">
+    <td align="right"><b><?php print_string('subject', 'forum'); ?>:</b></td>
+    <td colspan="3">
+        <input type="text" name="subject" size="80" value="<?php echo $form->subject; ?>" />
+    </td>
+</tr>
+<tr valign="top">
+    <td align="right"><b>
+     <?php print_string('message', 'forum'); ?>:</b></td>
+    <td colspan="3" rowspan="2" align="left">
+    <?php print_textarea($usehtmleditor, 25, 65, 630, 400, 'message', $form->message); ?>
+    </td>
+</tr>
+<tr valign="top">
+    <td align="right" valign="center" nowrap="nowrap">
+        <font size="2">
+            <?php
+                helpbutton('reading', get_string('helpreading'), 'moodle', true, true);
+                echo '<br />';
+                helpbutton('writing', get_string('helpwriting'), 'moodle', true, true);
+                echo '<br />';
+                if ($usehtmleditor) {
+                   helpbutton('richtext', get_string('helprichtext'), 'moodle', true, true);
+                } else {
+                   emoticonhelpbutton('theform', 'message');
+                } 
+            ?>
+        </font>
+    </td>
+</tr>
+
+<!-- Hiding format choice option from users as it is not applicable for us -->
+<!--<tr valign="top">
+    <td align="right"><b><?php print_string('formattexttype'); ?>:</b></td>
+    <td colspan="3">
+    <?php 
+        if ($usehtmleditor) {   /// Trying this out for a while
+            print_string('formathtml');
+            echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
+        } else {
+            choose_from_menu(format_text_menu(), 'format', $form->format, '');
+        }
+        helpbutton('textformat', get_string('helpformatting'));
+     ?>
+    </td>
+</tr>-->
+<?php 
+ 	echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
+?>
+
+
+
+<tr>
+    <td align="right" nowrap="nowrap"><strong><?php echo get_string('receipts', 'block_quickmail')?>:</strong></td>
+    <td>
+       <?php
+         echo get_string('no') . ' <input type="radio" name="receive_receipt" checked="yes" value="0"/>';
+         echo get_string('yes') . ' <input type="radio" name="receive_receipt" value="1"/>';
+       ?>
+    </td>
+</tr>
+
+<tr>
+    <td align="center" colspan="4">
+	<input type="hidden" name="mailuser" id="mailuser" value=""/>
+    <input type="hidden" name="attachids" id="attachids" value="attach_1"/> <!-- Keeps track of all the attachment field-->
+    <input type="hidden" name="sesskey" value="<?php echo $USER->sesskey; ?>" />
+	<input type="hidden" name="fromemail" value="<?php echo $USER->email; ?>" id="fromemail" />	
+    <input type="hidden" name="id" value="<?php echo $course->id; ?>" />
+    <input type="hidden" name="instanceid" value="<?php echo $instance->id; ?>" />
+    <input type="submit" name="cancel" value="<?php print_string('cancel') ?>" />
+    <input type="submit" name="sendemail" value="<?php print_string('sendemail', 'block_quickmail') ?>" onClick = "updateList()"/>
+    </td>
+</tr>
+</table>
+</form>
+<script language="Javascript">
+    createListObjects();
+</script>
Index: plugins/blocks/quickmail/email.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/quickmail/email.php,v
retrieving revision 1.20
diff -u -r1.20 email.php
--- plugins/blocks/quickmail/email.php	18 Mar 2009 01:09:12 -0000	1.20
+++ plugins/blocks/quickmail/email.php	9 Apr 2009 20:42:46 -0000
@@ -1,380 +1,598 @@
-<?php //$Id: email.php,v 1.20 2009/03/18 01:09:12 whchuang Exp $
-/**
- * email.php - Used by Quickmail for sending emails to users enrolled in a specific course.
- *      Calls email.hmtl at the end.
- *
- * @author Mark Nielsen (co-maintained by Wen Hao Chuang)
- * @special thanks for Neil Streeter to provide patches for GROUPS
- * @package quickmail
- **/
-    
-    require_once('../../config.php');
-    require_once($CFG->libdir.'/blocklib.php');
-
-    $id         = required_param('id', PARAM_INT);  // course ID
-    $instanceid = optional_param('instanceid', 0, PARAM_INT);
-    $action     = optional_param('action', '', PARAM_ALPHA);
-
-    $instance = new stdClass;
-
-    if (!$course = get_record('course', 'id', $id)) {
-        error('Course ID was incorrect');
-    }
-
-    require_login($course->id);
-    $context = get_context_instance(CONTEXT_COURSE, $course->id);
-
-    if ($instanceid) {
-        $instance = get_record('block_instance', 'id', $instanceid);
-    } else {
-        if ($quickmailblock = get_record('block', 'name', 'quickmail')) {
-            $instance = get_record('block_instance', 'blockid', $quickmailblock->id, 'pageid', $course->id);
-        }
-    }
-
-/// This block of code ensures that Quickmail will run 
-///     whether it is in the course or not
-    if (empty($instance)) {
-        $groupmode = groupmode($course);
-        if (has_capability('block/quickmail:cansend', get_context_instance(CONTEXT_BLOCK, $instanceid))) {
-            $haspermission = true;
-        } else {
-            $haspermission = false;
-        }
-    } else {
-        // create a quickmail block instance
-        $quickmail = block_instance('quickmail', $instance);
-        
-        $groupmode     = $quickmail->groupmode();
-        $haspermission = $quickmail->check_permission();
-    }
-    
-    if (!$haspermission) {
-        error('Sorry, you do not have the correct permissions to use Quickmail.');
-    }
-
-    if (!$courseusers = get_users_by_capability($context, 'moodle/course:view', 'u.*', 'u.lastname, u.firstname', '', '', '', '', false)) {
-        error('No course users found to email');
-    }
-
-    if ($action == 'view') {
-        // viewing an old email.  Hitting the db and puting it into the object $form
-        $emailid = required_param('emailid', PARAM_INT);
-        $form = get_record('block_quickmail_log', 'id', $emailid);
-        $form->mailto = explode(',', $form->mailto); // convert mailto back to an array
-
-    } else if ($form = data_submitted()) {   // data was submitted to be mailed
-        confirm_sesskey();
-
-        if (!empty($form->cancel)) {
-            // cancel button was hit...
-            redirect("$CFG->wwwroot/course/view.php?id=$course->id");
-        }
-        
-        // prepare variables for email
-        $form->subject = stripslashes($form->subject);
-        $form->subject = clean_param(strip_tags($form->subject, '<lang><span>'), PARAM_RAW); // Strip all tags except multilang
-        $form->message = clean_param($form->message, PARAM_CLEANHTML);
-
-        // make sure the user didn't miss anything
-        if (!isset($form->mailto)) {
-            $form->error = get_string('toerror', 'block_quickmail');
-        } else if (!$form->subject) {
-            $form->error = get_string('subjecterror', 'block_quickmail');
-        } else if (!$form->message) {
-            $form->error = get_string('messageerror', 'block_quickmail');
-        }
-
-        // process the attachment
-        $attachment = $attachname = '';
-        if (has_capability('moodle/course:managefiles', $context)) {
-            $form->attachment = trim($form->attachment);
-            if (isset($form->attachment) and !empty($form->attachment)) {
-                $form->attachment = clean_param($form->attachment, PARAM_PATH);
-            
-                if (file_exists($CFG->dataroot.'/'.$course->id.'/'.$form->attachment)) {
-                    $attachment = $course->id.'/'.$form->attachment;
-            
-                    $pathparts = pathinfo($form->attachment);
-                    $attachname = $pathparts['basename'];
-                } else {
-                    $form->error = get_string('attachmenterror', 'block_quickmail', $form->attachment);
-                }
-            }
-        } else {
-            require_once($CFG->libdir.'/uploadlib.php');
-        
-            $um = new upload_manager('attachment', false, true, $course, false, 0, true);
-
-            // process the student posted attachment if it exists
-            if ($um->process_file_uploads('temp/block_quickmail')) {
-                
-                // original name gets saved in the database
-                $form->attachment = $um->get_original_filename();
-
-                // check if file is there
-                if (file_exists($um->get_new_filepath())) {
-                    // get path to the file without $CFG->dataroot
-                    $attachment = 'temp/block_quickmail/'.$um->get_new_filename();
-                
-                    // get the new name (name may change due to filename collisions)
-                    $attachname = $um->get_new_filename();
-                } else {
-                    $form->error = get_string("attachmenterror", "block_quickmail", $form->attachment);
-                }
-            } else {
-                $form->attachment = ''; // no attachment
-            }
-        }
-           
-        // no errors, then email
-        if(!isset($form->error)) {
-            $mailedto = array(); // holds all the userid of successful emails
-            
-            // get the correct formating for the emails
-            $form->plaintxt = format_text_email($form->message, $form->format); // plain text
-            $form->html = format_text($form->message, $form->format);        // html
-
-            // run through each user id and send a copy of the email to him/her
-            // not sending 1 email with CC to all user ids because emails were required to be kept private
-            foreach ($form->mailto as $userid) {  
-                if (!$courseusers[$userid]->emailstop) {
-                    $mailresult = email_to_user($courseusers[$userid], $USER, $form->subject, $form->plaintxt, $form->html, $attachment, $attachname);
-                    // checking for errors, if there is an error, store the name
-                    if (!$mailresult || (string) $mailresult == 'emailstop') {
-                        $form->error = get_string('emailfailerror', 'block_quickmail');
-                        $form->usersfail['emailfail'][] = $courseusers[$userid]->lastname.', '.$courseusers[$userid]->firstname;
-                    } else {
-                        // success
-                        $mailedto[] = $userid;
-                    }
-                } else {
-                    // blocked email
-                    $form->error = get_string('emailfailerror', 'block_quickmail');
-                    $form->usersfail['emailstop'][] = $courseusers[$userid]->lastname.', '.$courseusers[$userid]->firstname;
-                }
-            }
-            
-            // cleanup - delete the uploaded file
-            if (isset($um) and file_exists($um->get_new_filepath())) {
-                unlink($um->get_new_filepath());
-            }
-
-            // prepare an object for the insert_record function
-            $log = new stdClass;
-            $log->courseid   = $course->id;
-            $log->userid     = $USER->id;
-            $log->mailto     = implode(',', $mailedto);
-            $log->subject    = addslashes($form->subject);
-            $log->message    = addslashes($form->message);
-            $log->attachment = $form->attachment;
-            $log->format     = $form->format;
-            $log->timesent   = time();
-            if (!insert_record('block_quickmail_log', $log)) {
-                error('Email not logged.');
-            }
-
-            if(!isset($form->error)) {  // if no emailing errors, we are done
-                // inform of success and continue
-                redirect("$CFG->wwwroot/course/view.php?id=$course->id", get_string('successfulemail', 'block_quickmail'));
-            }
-        }
-        // so people can use quotes.  It will display correctly in the subject input text box
-        $form->subject = s($form->subject);
-
-    } else {
-        // set them as blank
-        $form->subject = $form->message = $form->format = $form->attachment = '';
-    }
-
-/// Create the table object for holding course users in the To section of email.html
-    
-    // table object used for printing the course users
-    $table              = new stdClass;
-    $table->cellpadding = '10px';    
-    $table->width       = '100%';
-
-    $t    = 1;    // keeps track of the number of users printed (used for javascript)
-    $cols = 4;    // number of columns in the table
-
-    if ($groupmode == NOGROUPS) { // no groups, basic view
-        $table->head  = array();
-        $table->align = array('left', 'left', 'left', 'left');
-        $cells        = array();
-
-        foreach($courseusers as $user) { 
-            if (isset($form->mailto) && in_array($user->id, $form->mailto)) {
-                $checked = 'checked="checked"';
-            } else {
-                $checked = '';
-            }       
-        
-            $cells[] = "<input type=\"checkbox\" $checked id=\"mailto$t\" value=\"$user->id\" name=\"mailto[]\" />".
-                        "<label for=\"mailto$t\">".fullname($user, true).'</label>';
-            $t++;
-        }
-        $table->data = array_chunk($cells, $cols);
-    } else {
-        $groups      = new stdClass;    // holds the groups to be displayed
-        $buttoncount = 1;               // counter for the buttons (used by javascript)
-        $ingroup     = array();         // keeps track of the users that belong to groups
-        
-        // determine the group mode
-        if (has_capability('moodle/site:accessallgroups', $context)) {
-            // teachers/admins default to the more liberal group mode
-            $groupmode = VISIBLEGROUPS;
-        }
-        
-        // set the groups variable
-        switch ($groupmode) {
-            case VISIBLEGROUPS:
-                $groups = groups_get_all_groups($course->id);
-                break;
-
-            case SEPARATEGROUPS:
-                $groups = groups_get_all_groups($course->id,$USER->id);
-                break;
-        }
-
-        // Add a fake group for those who are not group members
-        $groups[] = 0;
-
-        $notingroup = array();
-        if ($allgroups = groups_get_all_groups($course->id)) {
-            foreach ($courseusers as $user) {
-                $nomembership = true;
-                foreach ($allgroups as $group) {
-                    if (groups_is_member($group->id, $user->id)) {
-                        $nomembership = false;
-                        break;
-                    }
-                }
-                if ($nomembership) {
-                    $notingroup[] = $user->id;
-                }
-            }
-        }
-
-        // set up the table
-        $table->head        = array(get_string('groups'), get_string('groupmembers'));
-        $table->align       = array('center', 'left');
-        $table->size        = array('100px', '*');
-        
-        foreach($groups as $group) {            
-            $start = $t;
-            $cells = array();  // table cells (each is a check box next to a user name)
-            foreach($courseusers as $user) { 
-                if (is_object( $group ) and groups_is_member($group->id, $user->id) or                    // is a member of the group or
-                   (!is_object( $group ) and $group == 0 and in_array($user->id, $notingroup)) ) {     // this is our fake group and this user is not a member of another group
-                                                    
-                    if (isset($form->mailto) && in_array($user->id, $form->mailto)) {
-                        $checked = 'checked="checked"';
-                    } else {
-                        $checked = '';
-                    }
-        
-                    $cells[] = "<input type=\"checkbox\" $checked id=\"mailto$t\" value=\"$user->id\" name=\"mailto[$user->id]\" />".
-                                "<label for=\"mailto$t\">".fullname($user, true).'</label>';
-                    $t++;
-                }
-            }
-            $end = $t;
-            
-            // cell1 has the group picture, name and check button
-            $cell1 = '';
-            if ( $group ) {
-                $cell1   .= print_group_picture($group, $course->id, false, true).'<br />';
-            }
-            if ($group) {
-                $cell1 .= groups_get_group_name($group->id);
-            } else {
-                $cell1 .= get_string('notingroup', 'block_quickmail');
-            }
-            if (count($groups) > 1 and !empty($cells)) {
-                $selectlinks = '<a href="javascript:void(0);" onclick="block_quickmail_toggle(true, '.$start.', '.$end.');">'.get_string('selectall').'</a> / 
-                                <a href="javascript:void(0);" onclick="block_quickmail_toggle(false, '.$start.', '.$end.');">'.get_string('deselectall').'</a>';
-            } else {
-                $selectlinks = '';
-            }
-            $buttoncount++;
-            
-            // cell2 has the checkboxes and the user names inside of a table
-            if (empty($cells) and !$group) {
-                // there is no one that is not in a group, so no need to print our 'nogroup' group
-                continue;
-            } else if (empty($cells)) {
-                // cells is empty, so there are no group members for that group
-                $cell2 = get_string('nogroupmembers', 'block_quickmail');
-            } else {
-                $cell2 = '<table cellpadding="5px">';
-                $rows = array_chunk($cells, $cols);
-                foreach ($rows as $row) {
-                    $cell2 .= '<tr><td nowrap="nowrap">'.implode('</td><td nowrap="nowrap">', $row).'</td></tr>';
-                }
-                $cell2 .= '</table>';
-            }
-            // add the 2 cells to the table
-            $table->data[] = array($cell1, $selectlinks.$cell2);
-        }
-    }
-
-    // get the default format       
-    if ($usehtmleditor = can_use_richtext_editor()) {
-        $defaultformat = FORMAT_HTML;
-    } else {
-        $defaultformat = FORMAT_MOODLE;
-    }
-    
-    // set up some strings
-    $readonly       = '';
-    $strchooseafile = get_string('chooseafile', 'resource');
-    $strquickmail   = get_string('blockname', 'block_quickmail');
-
-/// Header setup
-    if ($course->category) {
-        $navigation = "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->";
-    } else {
-        $navigation = '';
-    }
-
-    print_header($course->fullname.': '.$strquickmail, $course->fullname, "$navigation $strquickmail", '', '', true);
-
-    // print the email form START
-    print_heading($strquickmail);
-
-    // error printing
-    if (isset($form->error)) {
-        notify($form->error);
-        if (isset($form->usersfail)) {
-            $errorstring = '';
-
-            if (isset($form->usersfail['emailfail'])) {
-                $errorstring .= get_string('emailfail', 'block_quickmail').'<br />';
-                foreach($form->usersfail['emailfail'] as $user) {
-                    $errorstring .= $user.'<br />';
-                }               
-            }
-
-            if (isset($form->usersfail['emailstop'])) {
-                $errorstring .= get_string('emailstop', 'block_quickmail').'<br />';
-                foreach($form->usersfail['emailstop'] as $user) {
-                    $errorstring .= $user.'<br />';
-                }               
-            }
-            notice($errorstring, "$CFG->wwwroot/course/view.php?id=$course->id", $course);
-        }
-    }
-
-    $currenttab = 'compose';
-    include($CFG->dirroot.'/blocks/quickmail/tabs.php');
-
-    print_simple_box_start('center');
-    require($CFG->dirroot.'/blocks/quickmail/email.html');
-    print_simple_box_end();
-    
-    if ($usehtmleditor) {
-        use_html_editor('message');
-    }
-
-    print_footer($course);
-?>
+<?php // $Id: email.php,v 2.5 2008/02/15 09:53:43 pcali1 Exp $
+    
+    /**
+     *   Edited by: Philip Cali
+     *   Date: 2/15/08
+     *   Louisiana State University
+     */
+     
+    /**
+     * email.php - Used by Quickmail for sending emails to users enrolled in a specific course.
+     *      Calls email.html at the end.
+     *
+     * @Original author Mark Nielsen and Michael Penney. 
+     * @Updated by Bibek Bhattarai, Neha Arora, Wen Hao Chuang
+     * @version $Id: email.php,v 2.01 2007/04/05 09:55:18 wenhaochuang Exp $
+     * @package quickmailv2
+     **/
+    
+	/** 
+ 	* Updated feature:
+ 	*	- Replaces checkbox with selection list for effective usability in case of larger classes
+	* - For simplicity purpose removed the options group mailing for now, will be added in next version
+ 	**/ 
+
+    //Load libary files
+    require_once('../../config.php');
+    require_once("$CFG->dirroot/blocks/moodleblock.class.php");
+    require_once($CFG->libdir . '/accesslib.php');
+    require_once('block_quickmail.php');
+
+    //Check user have logged in to the system or not
+    require_login();
+
+	//Read parameter values courseid, quickmail instance id, and action  
+    $id = required_param('id', PARAM_INT);  // course id
+    $hidden = optional_param('hidden', 0, PARAM_BOOL);
+    $instanceid = required_param('instanceid', PARAM_INT);
+    $action = optional_param('action', '', PARAM_ALPHA);
+    
+	//Setup quickmail block
+    $quickmail = new block_quickmail();
+    $instance = new stdClass;
+    
+    //If course doesnot exists error out
+    if (! $course = get_record('course', 'id', $id)) {
+        error(get_string('incorrect_id', 'block_quickmail'));
+    }
+
+    //Makes sure we're ina the right context
+    if (!$context = get_context_instance(CONTEXT_COURSE, $course->id)){
+        error(get_string('wrong_context', 'block_quickmail'));
+    }
+    
+	//Have to figure out .............................. Bibek
+    $quickmailresult = get_record('block', 'name', 'quickmail');
+    if ($instanceid && $quickmailresult) {
+      $instance = get_record('block_instance', 'id', $instanceid, 'blockid', $quickmailresult->id);
+      if (!$instance){
+          $instance = get_record('block_pinned', 'id', $instanceid, 'blockid', $quickmailresult->id);
+      }
+   }
+
+/// This block of code ensures that Quickmail will run 
+/// whether it is in the course or not
+
+    if (empty($instance)) {
+        $groupmode = $course->groupmode;
+        if (isGuest()) {
+            $haspermission = false;
+        } else {
+            $haspermission = true;
+        }
+    } else {
+        // create a quickmail block instance
+        $quickmail->_load_instance($instance);
+        $quickmail->load_defaults();
+        
+        $groupmode      = $quickmail->groupmode();
+        $haspermission  = $quickmail->check_permission('block/quickmail:cansend', CONTEXT_COURSE, $course) || 
+                          $quickmail->allow_students_to_email($USER->id);
+    }
+   
+ 
+	if(!$quickmail->check_permission('block/quickmail:canimpersonate', CONTEXT_COURSE, $course) && !isset($USER->id)){
+		error(get_string('wrong_user', 'block_quickmail'));
+	}
+
+    if (!$haspermission) {
+        error(get_string('no_permission', 'block_quickmail'));
+    }
+
+    $groupmembers_to_groupid = array();
+    $roles_to_userid = array();
+    $courseusers = array();
+
+    $groups = get_records('groups', 'courseid', $course->id, 'name asc');
+    
+    $sql = "SELECT DISTINCT CONCAT(r.id, '_', usr.username), r.id AS roleid, r.name, 
+            r.shortname, usr.id AS userid, usr.username, usr.email, usr.firstname, 
+            usr.lastname
+     FROM mdl_course AS c         
+        INNER JOIN mdl_context AS cx ON cx.id={$context->id}
+        INNER JOIN mdl_role_assignments AS ra ON cx.id = ra.contextid
+        INNER JOIN mdl_role AS r ON ra.roleid = r.id
+        INNER JOIN mdl_user AS usr ON ra.userid = usr.id
+     WHERE (c.id = {$course->id}) ORDER BY usr.lastname ASC";
+
+    $dbcontent = get_records_sql($sql);
+
+    $sql = "SELECT CONCAT(u.id, '_', u.username, '_', g.id) AS uniquecode, 
+                   u.id AS userid, g.id AS groupid, g.name 
+            FROM mdl_user AS u, 
+                 mdl_groups AS g, 
+                 mdl_groups_members AS gm 
+            WHERE g.courseid = {$course->id} 
+                AND g.id = gm.groupid 
+                AND gm.userid = u.id";
+
+    $groupcontent = get_records_sql($sql);
+
+    foreach($dbcontent as $content_record) {
+        $userid = $content_record->userid;
+        $roleid = $content_record->roleid;
+
+        if (!isset($roles_to_userid[$userid])){
+            $roles_to_userid[$userid] = array();
+        }
+
+        $role = new stdClass;
+        $role->name = $content_record->name;
+        $role->shortname = $content_record->shortname;
+        $roles_to_userid[$userid][] = $role;
+
+        foreach ($groups as $group) {
+	    $index = $userid .'_'. $content_record->username .'_'. $group->id;
+	    if (array_key_exists($index, $groupcontent)) {
+
+            	$record = $groupcontent[$index];
+                if (!isset($groupmembers_to_groupid[$record->userid])) {
+                    $groupmembers_to_groupid[$record->userid] = array();
+                }
+            
+                if (isset($groupmembers_to_groupid[$record->userid][$record->groupid])) {
+                    continue;
+                }
+                $groupmembers_to_groupid[$record->userid][$record->groupid] = $groups[$record->groupid];
+            }
+        }
+
+        if (isset($courseusers[$userid])) {
+            continue;
+        }
+
+        $user = new stdClass;
+        $user->firstname = $content_record->firstname;
+        $user->lastname = $content_record->lastname;
+        $user->email = $content_record->email;
+        $user->id = $userid;
+        $courseusers[$userid] = $user;
+    }
+
+	//Get list of users enrolled in the course including teachers and students
+    if (!$courseusers) {
+        error('No course users found to email');
+    }
+
+	// set up some strings
+    $readonly       = '';
+    $strchooseafile = get_string('chooseafile', 'resource');
+    $strquickmail   = get_string('blockname', 'block_quickmail');
+ 
+    $navigation = array(
+                array('name' => $course->shortname, 'link' => "{$CFG->wwwroot}/course/view.php?id=$course->id", 'type'=> 'title'),
+                array('name' => $strquickmail, 'link'=>'', 'type'=>'title'),
+                );
+ 
+    print_header_simple($strquickmail, '', build_navigation($navigation));
+
+  // if action is view display the email user wants to view
+	if ($action == 'view') {
+        // viewing an old email.  Hitting the db and puting it into the object $form
+        $emailid = required_param('emailid', PARAM_INT);
+        $form = get_record('block_quickmail_log', 'id', $emailid);
+        $mail_list = explode(',', stripslashes($form->mailto)); // convert mailto back to an array        
+    } 
+	else if ($form = data_submitted()) {   // data was submitted to be mailed
+    	confirm_sesskey();
+
+        if (!empty($form->cancel)) {
+            // cancel button was hit...
+            redirect("$CFG->wwwroot/course/view.php?id=$course->id");
+        }
+        
+        // prepare variables for email      
+        $form->subject = stripslashes($form->subject);
+        $form->subject = clean_param($form->subject, PARAM_CLEAN);
+        $form->subject = strip_tags($form->subject, '<lang>');        // Strip all tags except lang
+        $form->subject = break_up_long_words($form->subject);
+
+        $form->message = stripslashes($form->message); // needed to get slashes off of the post
+        $form->message = clean_param($form->message, PARAM_CLEANHTML);
+
+        // get the correct formating for the emails
+        $form->plaintxt = format_text_email($form->message, $form->format); // plain text
+        $form->html = format_text($form->message, $form->format);        // html
+       	$mail_list = explode(',',stripslashes($form->mailuser));
+		
+        //multiple attachments
+        $attach_list = explode(',', stripslashes($form->attachids));
+
+		// make sure the user didn't miss anything
+		if (sizeof($mail_list)<=1 && $mail_list[0]=="") {
+            $form->error = get_string('toerror', 'block_quickmail');
+        } /*else if (!$form->subject) {
+            $form->error = get_string('subjecterror', 'block_quickmail');
+        } else if (!$form->message) {
+            $form->error = get_string('messageerror', 'block_quickmail');
+        }*/
+        
+        // process the attachment
+        $attachment = array();
+        
+		require_once($CFG->libdir.'/uploadlib.php');
+        
+        foreach ($attach_list as $attach_id) {
+            $um = new upload_manager($attach_id, false, true, $course, false, 0, true);
+			$attachment_success = true;
+            
+			// process the student posted attachment if it exists
+            foreach ($_FILES as $name => $file){
+				$file['originalname'] = $file['name'];
+			}
+			$attachment_success = $um->process_file_uploads('temp/block_quickmail');
+			if ($attachment_success) {
+                // original name gets saved in the database
+                $form->attachment .= $um->get_original_filename() .' ';
+				// check if file is there
+                if (file_exists($um->get_new_filepath())) {
+                    // get path to the file without $CFG->dataroot
+                    $attachment[$um->get_new_filename()] = 'temp/block_quickmail/'.$um->get_new_filename();
+                    //$attachment = 'temp/block_quickmail/'.$um->get_new_filename();
+                	
+                    // get the new name (name may change due to filename collisions)
+                    //$attachname = $um->get_new_filename();
+                } else {
+                    $form->error = get_string("attachmenterror", "block_quickmail", $form->attachment);
+                }
+            } 
+			elseif($file['originalname']!='' && !$attachment_sucess){
+				$form->error = get_string("attachmentmaxsize", "block_quickmail", $form->attachment);
+			}
+			else{
+				$form->attachment .= ''; // no attachment
+            }
+        }        
+        
+        // no errors, then email
+        if(!isset($form->error)) {
+            $mailedto = array(); // holds all the userid of successful emails
+            $blockedTo = array();
+			$failedTo = array();
+            //print_heading(get_string('pleasewait', 'block_quickmail'), 'center', 3);  // inform the user to wait
+
+            // run through each user id and send a copy of the email to him/her
+            // not sending 1 email with CC to all user ids because emails were required to be kept private
+            foreach ($mail_list as $userid) {
+				$userid = stripslashes($userid);
+				$userid = str_replace("\"","",$userid);
+				//$userid =   
+                if (!$courseusers[$userid]->emailstop) {
+                     //if($userid != $USER->id){
+						$mailresult = modified_email_to_user($courseusers[$userid], $USER, $form->subject, 
+                                        $form->plaintxt, $form->html, $attachment);
+                    	// checking for errors, if there is an error, store the name
+                    	if (!$mailresult || (string) $mailresult == 'emailstop') {
+                        	$form->error = get_string('emailfailerror', 'block_quickmail');
+                        	$form->usersfail['emailfail'][] = $courseusers[$userid]->lastname.', '.$courseusers[$userid]->firstname;
+							$failedTo[] = $userid;
+                    	} else {
+                        	// success
+                        	$mailedto[] = $userid;						
+                    	}
+					//}
+                } else {
+                    // blocked email
+                    $form->error = get_string('emailfailerror', 'block_quickmail');
+                    $form->usersfail['emailstop'][] = $courseusers[$userid]->lastname.', '.$courseusers[$userid]->firstname;
+					$blockedTo[] = $userid;
+                }
+            }
+
+            if ($form->receive_receipt) {
+            if(count($mailedto)>0){
+				$messagetext = $messagetext."----------------------------------------------------\n";
+				$messagetext = $messagetext."Following email was successfully sent to: \n";
+				$messagetext = $messagetext."----------------------------------------------------\n";				
+				foreach($mailedto as $userid){
+					$messagetext = $messagetext.$courseusers[$userid]->firstname." ".$courseusers[$userid]->lastname.";\t";
+				}
+				$messagetext = $messagetext."\n";
+			}
+			
+			if(count($blockedTo)>0){
+				$messagetext = $messagetext."\n-------------------------------------------------------------------------------\n";
+				$messagetext = $messagetext."Following user(s) have chosen not to recieve any email through Moodle: \n";
+				$messagetext = $messagetext."-------------------------------------------------------------------------------\n";
+				foreach($blockedTo as $userid){
+					$messagetext = $messagetext.$courseusers[$userid]->firstname." ".$courseusers[$userid]->lastname.";\t";
+				}
+				$messagetext = $messagetext."\n";
+			}
+			
+			if(count($failedTo)>0){
+				$messagetext = $messagetext."\n---------------------------------------------------------------------------------------------------------------\n";
+				$messagetext = $messagetext."Moodle was unable to send email to following user(s), please contact Moodle support to report the error: \n";
+				$messagetext = $messagetext."-----------------------------------------------------------------------------------------------------------------\n";
+				foreach($failedTo as $userid){
+					$messagetext = $messagetext.$courseusers[$userid]->firstname." ".$courseusers[$userid]->lastname.";\t";
+				}
+				$messagetext = $messagetext."\n";
+			}
+			
+			$messagetext = $messagetext."\n==================================\nMessage Content\n----------------------------------\n";
+			$messagetext = $messagetext."\n".$form->plaintxt;
+			$messagetext = $messagetext."\n\n=================================\n";
+			$form->subject = "Quickmail dispatch receipt: ".$form->subject;
+			$mailresult = modified_email_to_user($USER, $USER, $form->subject, $messagetext, '', $attachment);
+            }
+
+            // cleanup - delete the uploaded file
+            if (isset($um) and file_exists($um->get_new_filepath())) {
+                unlink($um->get_new_filepath());
+            }
+
+            // prepare an object for the insert_record function
+            $emaillog = new stdClass;
+            $emaillog->courseid   = $course->id;
+            $emaillog->userid     = $USER->id;
+            $emaillog->mailto     = implode(',', $mailedto);
+            $emaillog->subject    = addslashes($form->subject);
+            $emaillog->message    = addslashes($form->message);
+            $emaillog->attachment = $form->attachment;
+            $emaillog->format     = $form->format;
+            $emaillog->timesent   = time();
+			
+			if (!insert_record('block_quickmail_log', $emaillog)) {
+                error('Email not logged.');
+            }
+
+            if(!isset($form->error)) {  // if no emailing errors, we are done
+                // inform of success and continue
+                redirect("$CFG->wwwroot/course/view.php?id=$course->id", get_string('successfulemail', 'block_quickmail'));
+                print_footer($course);
+                exit();
+            }
+        }
+        // so people can use quotes.  It will display correctly in the subject input text box
+        $form->subject = htmlentities($form->subject, ENT_QUOTES);  
+
+    } else {
+        // set them as blank
+        $form->subject = $form->message = $form->format = $form->attachment = '';		
+    }
+
+    // get the default format       
+    if ($usehtmleditor = can_use_richtext_editor()) {
+        $defaultformat = FORMAT_HTML;
+    } else {
+        $defaultformat = FORMAT_MOODLE;
+    }
+
+    // print the email form START
+    print_heading($strquickmail);
+    
+    // error printing
+    if (isset($form->error)) {
+        echo '<b><center><font color="#FF0000" align="center"> There was an error, please contact your Moodle administrator.';
+		notify($form->error);
+		echo '</font></center></b>';
+        if (isset($form->usersfail)) {
+            $errorstring = '';
+            
+            if (isset($form->usersfail['emailfail'])) {
+                $errorstring .= get_string('emailfail', 'block_quickmail').'<br />';
+                foreach($form->usersfail['emailfail'] as $user) {
+                    $errorstring .= $user.'<br />';
+                }               
+            }
+
+            if (isset($form->usersfail['emailstop'])) {
+                $errorstring .= get_string('emailstop', 'block_quickmail').'<br />';
+                foreach($form->usersfail['emailstop'] as $user) {
+                    $errorstring .= $user.'<br />';
+                }               
+            }
+            notify($errorstring);
+            
+            // print continue button
+            print_continue("$CFG->wwwroot/course/view.php?id=$course->id");
+            print_footer($course);
+            exit();
+        }
+    }
+
+ 	print_simple_box_start('center'); 	       
+	require('email.html');  // email form
+    print_simple_box_end();
+    
+    if ($usehtmleditor) {
+        use_html_editor('message');
+    }
+
+    print_footer($course);
+
+    //////////////MODIFIED EMAIL TO USER FUNCTION////////////////////
+    function modified_email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment=null, $usetrueaddress=true, $replyto='', $replytoname='') {
+        global $CFG, $FULLME;
+
+        include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
+        $textlib = textlib_get_instance();
+        
+        if (empty($user)) {
+             return false;
+        } 
+
+        // skip mail to suspended users
+        if (isset($user->auth) && $user->auth=='nologin') {
+            return true;
+        }
+
+        if (!empty($user->emailstop)) {
+            return 'emailstop';
+        }
+                       
+        if (over_bounce_threshold($user)) {
+            error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
+            return false;
+        }
+
+        $mail = new phpmailer;
+         
+        $mail->Version = 'Moodle '. $CFG->version;           // mailer version
+        $mail->PluginDir = $CFG->libdir .'/phpmailer/';      // plugin directory (eg smtp plugin)
+                 
+        $mail->CharSet = 'UTF-8';
+                          
+          // some MTAs may do double conversion of LF if CRLF used, CRLF is required line ending in RFC 822bis
+            // hmm, this is a bit hacky because LE should be private
+        if (isset($CFG->mailnewline) and $CFG->mailnewline == 'CRLF') {
+             $mail->LE = "\r\n";
+        } else {
+             $mail->LE = "\n";
+        }
+                                                              
+        if ($CFG->smtphosts == 'qmail') {
+              $mail->IsQmail();                              // use Qmail system
+                                                                                     
+        } else if (empty($CFG->smtphosts)) {
+             $mail->IsMail();                               // use PHP mail() = sendmail
+                                                                                          
+        } else {
+             $mail->IsSMTP();                               // use SMTP directly
+             if (!empty($CFG->debugsmtp)) {
+                echo '<pre>' . "\n";
+                $mail->SMTPDebug = true;
+              }
+             $mail->Host = $CFG->smtphosts;               // specify main and backup servers
+                                                                                                                                                                  
+             if ($CFG->smtpuser) {                          // Use SMTP authentication
+               $mail->SMTPAuth = true;
+               $mail->Username = $CFG->smtpuser;
+               $mail->Password = $CFG->smtppass;
+            }
+        }
+        
+        $supportuser = generate_email_supportuser();
+                
+                 
+              // make up an email address for handling bounces
+        if (!empty($CFG->handlebounces)) {
+            $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
+            $mail->Sender = generate_email_processing_address(0,$modargs);
+        } else {
+            $mail->Sender   = $supportuser->email;
+        }
+                                                             
+        if (is_string($from)) { // So we can pass whatever we want if there is need
+            $mail->From     = $CFG->noreplyaddress;
+            $mail->FromName = $from;
+        } else if ($usetrueaddress and $from->maildisplay) {
+            $mail->From     = $from->email;
+            $mail->FromName = fullname($from);
+        } else {
+            $mail->From     = $from->email;
+            $mail->FromName = fullname($from);
+            if (empty($replyto)) {
+              $mail->AddReplyTo($CFG->noreplyaddress,get_string('noreplyname'));
+           }
+       }
+
+       if (!empty($replyto)) {
+         $mail->AddReplyTo($replyto,$replytoname);
+     }
+ 
+     $mail->Subject = substr(stripslashes($subject), 0, 900);
+ 
+     $mail->AddAddress($user->email, fullname($user) );
+ 
+     $mail->WordWrap = 79;                               // set word wrap
+ 
+     if (!empty($from->customheaders)) {                 // Add custom headers
+         if (is_array($from->customheaders)) {
+             foreach ($from->customheaders as $customheader) {
+                 $mail->AddCustomHeader($customheader);
+             }
+         } else {
+             $mail->AddCustomHeader($from->customheaders);
+         }
+     }
+ 
+     if (!empty($from->priority)) {
+         $mail->Priority = $from->priority;
+     }
+ 
+     if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
+         $mail->IsHTML(true);
+         $mail->Encoding = 'quoted-printable';           // Encoding to use
+         $mail->Body    =  $messagehtml;
+         $mail->AltBody =  "\n$messagetext\n";
+     } else {
+         $mail->IsHTML(false);
+     $mail->Body =  "\n$messagetext\n";
+     }
+ 
+     if ($attachment) {
+        foreach ($attachment as $attachname => $attachvalue) {
+         if (ereg( "\\.\\." ,$attachvalue )) {    // Security check for ".." in dir path
+             $mail->AddAddress($supportuser->email, fullname($supportuser, true) );
+             $mail->AddStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
+         } else {
+             require_once($CFG->libdir.'/filelib.php');
+             $mimetype = mimeinfo('type', $attachname);
+             $mail->AddAttachment($CFG->dataroot .'/'. $attachvalue, $attachname, 'base64', $mimetype);
+         }
+
+        }
+     }
+ 
+ 
+ /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
+ /// encoding to the specified one
+     if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
+     /// Set it to site mail charset
+         $charset = $CFG->sitemailcharset;
+     /// Overwrite it with the user mail charset
+         if (!empty($CFG->allowusermailcharset)) {
+             if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
+                 $charset = $useremailcharset;
+             }
+         }
+     /// If it has changed, convert all the necessary strings
+         $charsets = get_list_of_charsets();
+         unset($charsets['UTF-8']);
+         if (in_array($charset, $charsets)) {
+         /// Save the new mail charset
+             $mail->CharSet = $charset;
+         /// And convert some strings
+             $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet); //From Name
+             foreach ($mail->ReplyTo as $key => $rt) {                                      //ReplyTo Names
+                 $mail->ReplyTo[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet);
+             }
+             $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet);   //Subject
+             foreach ($mail->to as $key => $to) {
+                 $mail->to[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet);      //To Names
+             }
+             $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet);         //Body
+             $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet);   //Subject
+         }
+     }
+ 
+     if ($mail->Send()) {
+         set_send_count($user);
+         $mail->IsSMTP();                               // use SMTP directly
+         if (!empty($CFG->debugsmtp)) {
+             echo '</pre>';
+         }
+         return true;
+     } else {
+         mtrace('ERROR: '. $mail->ErrorInfo);
+         add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
+         if (!empty($CFG->debugsmtp)) {
+             echo '</pre>';
+         }
+         return false;        
+      }
+    }
+
+?>
Index: plugins/blocks/quickmail/changes.txt
===================================================================
RCS file: plugins/blocks/quickmail/changes.txt
diff -N plugins/blocks/quickmail/changes.txt
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ plugins/blocks/quickmail/changes.txt	1 Jan 1970 00:00:00 -0000
@@ -0,0 +1,30 @@
+CHANGES
+=======
+
+Version 2.5.1 (released on Feb 18, 2008)
+
+(Feb 12, 2008)
+ - Added javascript for multiple attachments; also added support in the code
+
+(Feb 5, 2008)
+ - Added a filter for selection by roles. Gave the user the ability to select whether or not they wish to receive receipts
+
+(Jan 15, 2008)
+ - Added support to select by "Groups" or "Sections" of people
+
+Changes made by Philip Cali (pcali1 at lsu dot edu)
+
+Version 2.0.3 (released on Sep 18, 2007)
+----------------------------------------
+
+(Sep 18, 2007)
+ - Added some more language packs from the original quickmail and fix some issues in the /lang
+
+(Jul 24, 2007)
+ - Minor fixed the &lt and &gt (arrows) to use $THEME->larrow and $THEME->rarrow (contributed by Cliff Tham)
+
+(Jul 05, 2007)
+ - Fixed for some browser compatibility issues such as Safari. Problem is in selection.js where it reference listbox elements as selectedList.item(i). Safari doesn't support the "item" property and requires use of the "options" property, as in selectedList.options.item(i) or selectedList.options[i]. Thanks for Slobodan Jovcic pointed this out.
+
+Maintained by Wen-Hao Chuang (enwen at sfsu dot edu)
+
Index: plugins/blocks/quickmail/config_form.php
===================================================================
RCS file: plugins/blocks/quickmail/config_form.php
diff -N plugins/blocks/quickmail/config_form.php
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ plugins/blocks/quickmail/config_form.php	1 Jan 1970 00:00:00 -0000
@@ -0,0 +1,51 @@
+<?php // $Id: config_form.php,v 2.5 2008/02/15 09:53:43 pcali1 Exp $
+
+/**
+ *   Author: Philip Cali
+ *   Date: 2/15/08
+ *   Louisiana State University
+ *   
+ *   Moodle form for configuring the Quickmail block
+ */
+
+require_once($CFG->libdir . '/formslib.php');
+
+define('STUDENT_SELECT', 'allowstudents');
+define('ROLE_SELECT', 'roleselection');
+define('COURSE_ID', 'id');
+define('INSTANCE_ID', 'instanceid');
+
+class config_form extends moodleform {
+    
+    function definition() {
+        global $CFG, $USER;
+
+        $form=&$this->_form;
+
+        /*original select*/
+        $student_select = array(0 => get_string('no'), 1=>get_string('yes'));
+        $form->addElement('select', STUDENT_SELECT, get_string('allowstudents', 'block_quickmail'), $student_select);
+
+
+        $form->addElement('static', 'static_role', get_string('select_roles', 'block_quickmail'), '');
+        
+        $roles = get_records('role');
+        $role_select = array();
+        foreach ($roles as $role) {
+            $form->addElement('checkbox', ROLE_SELECT. ':'. $role->shortname, '', $role->name);
+        }
+
+        //hidden fields needed to process the form
+        $form->addElement('hidden', COURSE_ID, '');
+        $form->addElement('hidden', INSTANCE_ID, '');
+
+        $buttonarray = array();
+        $buttonarray[] = &$form->createElement('submit', 'submitbutton', 
+                                 get_string('submit', 'block_quickmail'));
+        $buttonarray[] = &$form->createElement('cancel');
+        $form->addGroup($buttonarray, 'buttonarr', '', array(' '), false);
+        $form->closeHeaderBefore('buttonarr');
+    }
+}
+
+?>
Index: plugins/blocks/quickmail/selection.js
===================================================================
RCS file: plugins/blocks/quickmail/selection.js
diff -N plugins/blocks/quickmail/selection.js
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ plugins/blocks/quickmail/selection.js	1 Jan 1970 00:00:00 -0000
@@ -0,0 +1,275 @@
+/**
+ * selection.js - Defines functions used by email.html in quickmail package
+ *
+ * Edited by: Philip Cali
+ * 2008/02/15 15:03:00
+ *
+ * @author: Bibek Bhattarai and Wen Hao Chuang
+ * 2007/03/29 09:00:00 
+ * @package quickmailv2
+ **/
+
+//Global variables used for pointing to members and mailto selection list
+var selectedList;
+var availableList;
+var availablegroups;
+var availableRoles;
+var oldGroupList;
+var newList;
+var selectedGroupidList;
+
+/** This function initializes selectedlist and availablelist with members and mailto selection lists respectively.
+  * This function is called everytime html form is reloaded 
+  **/
+function createListObjects(){
+    //availableRoles points to the role filter list, that holds a list of "filters"
+    availableRoles = document.getElementById("roles");
+    //availablegroups points to the groups list, that holds a list of groups/sections in a course
+    availablegroups = document.getElementById("groups");
+	//availablelist points to members list, that holds list of users (Teachers and Students) present in the class
+	availableList = document.getElementById("members");
+	//Selectedlist points to mailto list, that holds list of users (Teachers and Students) to which email has to be sent
+	selectedList = document.getElementById("mail_to");
+
+    oldGroupList = singlePassPreviousList(availablegroups);
+}
+
+function singlePassPreviousList(passedList) {
+    selectedGroupidList = new Array();
+    list = new Array(passedList.options.length);
+    for (var i=0; i< passedList.options.length; i++) {
+        list[i] = passedList.options[i].selected;
+        if (list[i]) {
+            var val = passedList.options[i].value;
+            var vararr = val.split(" ");
+            selectedGroupidList.push(vararr[0]);
+        }
+    }
+    
+    selectedGroupidList.push("");
+    return list;
+}
+
+//apply filter to select_users
+function special_select_users() {
+      if (!availableRoles){
+        createListObjects();
+      }
+      select_users(availablegroups, availableRoles.options[availableRoles.selectedIndex].value);
+}
+
+//abstract select users
+function select_users(list, filter) {
+    // select all the users that belong to that group
+    if (list == null) {
+        return;
+    }    
+
+    newList = singlePassPreviousList(list);
+    differentIndexes = oldGroupList.diff(newList);    
+    
+
+    if (differentIndexes != null) {
+      for (var index =0; index < differentIndexes.length; index++) {
+        if (list.options[differentIndexes[index]]){
+            var selected = list.options[differentIndexes[index]].selected;
+            var interestarr = list.options[differentIndexes[index]].value.split(" ");
+            var interest = interestarr[0];
+        }
+        var role_filter = (filter==null) ? "none" : filter;
+
+        if (selected) {
+            select_list(availableList, interest, role_filter);
+            select_list(selectedList, interest, role_filter);
+        } else {
+            deselect_list(availableList, interest, role_filter);
+            deselect_list(selectedList, interest, role_filter);
+        }
+
+      }
+    }
+
+    oldGroupList = newList;
+}
+
+function deselect_list(list, interest, filter) {
+    for (var j=list.length-1; j>=0; j--) {
+        var val = list.options[j].value;
+        var vararr = val.split(" ");
+        var groups = vararr[2].split(",");
+        var roles = vararr[3].split(",");
+        if (groups.contains(interest)) {
+            if (groups.length ==2) {
+                list.options[j].selected = false;
+            } else if (!checkAllGroups(groups, selectedGroupidList)){
+                list.options[j].selected = false;
+            } else if (filter != "none" && !roles.contains(filter)) {
+                list.options[j].selected = false;
+            }
+        }
+    }
+}
+
+function checkAllGroups(list1, list2) {
+    for (var i =0; i< list1.length; i++) {
+        if (list2.contains(list1[i])) {
+            return true;
+        }
+    }
+    return false;
+}
+
+function select_list(list, interest, filter) {
+    for (var j=list.length-1; j>=0; j--) {
+        var val = list.options[j].value;
+        var vararr = val.split(" ");
+        var groups = vararr[2].split(",");
+        var roles = vararr[3].split(",");
+        if (groups.contains(interest)) {
+            if (filter == "none" || roles.contains(filter)) {
+                list.options[j].selected = true;
+            }    
+        }
+    }
+}
+
+/** This function is used to remove user from selected list and add it back to available list */
+function remove_user(){
+	//for all items in selected list
+	for(var i=selectedList.length-1; i>=0; i--){
+		//if selected, append the user to available list. 
+		//Append will automatically remove it from selected list
+		if(selectedList.options[i].selected == true){
+		    availableList.appendChild(selectedList.options[i]);
+		}		
+	}
+	//call selectnone function to remove selection/highlight after move
+	selectNone(selectedList, availableList, availablegroups);	
+}
+
+/** This function is used to add user to selectedlist and remove it from available list */
+function add_user(){
+	//for all items in available list
+	for(var i=availableList.length-1; i>=0; i--){
+		//if selected, append the user to selected list.
+		//Append will automatically remove it from available list
+		if(availableList.options[i].selected == true){
+			selectedList.appendChild(availableList.options[i]);
+		}
+	}
+
+	//call selectnone function to remove selection/hightlight after move
+	selectNone(selectedList, availableList, availablegroups);	
+}
+
+/** This function is used to remove all users from selectionlist and add them to available list */
+function removeAll(){
+	var len = selectedList.length-1;
+	//Select all users in selected list and append them to available list
+	for(i=len; i>=0; i--){
+		availableList.appendChild(selectedList.options[i]);	
+	}
+	//De-select all users after move
+	selectNone(selectedList, availableList, availablegroups);	
+}
+
+/** This function is used to add all users from availablelist to selectionlist*/
+function addAll(){
+	var len = availableList.length - 1;
+	//Select all users from availablelist and append them to selectedlist
+	for(i=len; i>=0; i--){
+		selectedList.appendChild(availableList.options[i]);
+	}
+	//De-select all users after move
+	selectNone(selectedList, availableList, availablegroups);
+}
+
+/** This function is used to deselect users in availablelist, selectedlist after move */
+function selectNone(list1, list2, list3){
+	//Set all elements on list1 to selected false
+	for(var i=list1.length-1; i>=0 ; i--){
+		list1.options[i].selected = false;		
+	}
+	//Set all elements on list2 to selected false
+	for(var i=list2.length-1; i>=0; i--){
+		list2.options[i].selected = false;
+	}
+    //Set all elements on list3 to selected false
+    for (var i=list3.length-1; i>=0; i--){
+        list3.options[i].selected = false;
+    }
+}
+
+/** This function is used to construct the list of user to whom email has to be sent */
+function updateList(){
+	var ids = '';
+	// add user id of all elements in seleted list to string email as comma seperated value
+	for(var i=selectedList.length-1; i>=0 ; i--){
+		var val = selectedList.options[i].value;
+		var valarr = val.split(" ");
+		val = valarr[0];
+		ids = ids+val;
+		//do not add "," after last element
+		if(i!=0){
+			ids = ids+',';		
+		}
+	}
+	//set hidden input value mailuser as email
+	document.getElementById("mailuser").value = ids ;	
+}
+
+/** This function is used to construct the list of user to whom email has to be sent.
+	This function builds list of emails to be sent through external client*/
+function mail_to_ext_client(){
+	var emails = '';
+	// add user id of all elements in seleted list to string email as comma seperated value
+	for(var i=selectedList.length-1; i>=0 ; i--){
+		var val = selectedList.options[i].value;
+		var valarr = val.split(" ");
+		val = valarr[1];
+		emails = emails+val;
+		//do not add "," after last element
+		if(i!=0){
+			emails = emails+',';		
+		}
+	}
+	from_email = document.getElementById("fromemail").value;
+	//Redirects to external client with list of emails as bcc recievers
+	location.href='mailto:'+from_email+'?bcc='+emails;
+}
+
+
+
+Array.prototype.contains = function(element) {
+    if (element == null || element == '') {
+        return false;
+    }
+
+    for (var i =0; i< this.length; i++) {
+        if (this[i] == element) {
+            return true;
+        }
+    }
+    return false;
+}
+
+Array.prototype.diff = function(secondArray) {
+    if (secondArray == null) {
+        return null;
+    }
+
+    if (this.length != secondArray.length) {
+        return null;
+    }
+
+    diffList = new Array();
+
+    for (var i=0; i < secondArray.length ; i++) {
+        if (this[i] != secondArray[i]) {
+            diffList.push(i);
+        }
+    }
+
+    return diffList;
+}
+
Index: plugins/blocks/quickmail/quickmail_config.php
===================================================================
RCS file: plugins/blocks/quickmail/quickmail_config.php
diff -N plugins/blocks/quickmail/quickmail_config.php
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ plugins/blocks/quickmail/quickmail_config.php	1 Jan 1970 00:00:00 -0000
@@ -0,0 +1,108 @@
+<?php // $Id: quickmail_config.php,v 2.5 2008/02/15 09:53:43 pcali1 Exp $
+
+/**
+ *   Author: Philip Cali
+ *   Date: 2/15/2008
+ *   Louisiana State University
+ *
+ *   Moodle form for the quickmail config
+ */
+
+require_once('../../config.php');
+require_once("$CFG->dirroot/blocks/moodleblock.class.php");
+require_once('config_form.php');
+require_once($CFG->libdir . '/accesslib.php');
+require_once('block_quickmail.php');
+
+require_login();
+
+// get the course id, and block instanceid
+$id = required_param('id', PARAM_INT);
+$instanceid = optional_param('instanceid', 0, PARAM_INT);
+
+$quickmail = new block_quickmail();
+$instance = new stdClass;
+
+
+if (!$course = get_record('course', 'id', $id)) {
+    error('Could not load course!');
+}
+
+$pinned = false;
+
+//determine whether this instance is a pinned block, or regular instance
+ if ($instanceid && $quickmailblock = get_record('block', 'name', 'quickmail')) {
+    $instance = get_record('block_instance', 'id', $instanceid, 'blockid', $quickmailblock->id);
+    if (!$instance){
+        $pinned = true;
+        $instance = get_record('block_pinned', 'id', $instanceid, 'blockid', $quickmailblock->id);
+    }
+ }
+
+$quickmail->_load_instance($instance);
+$quickmail->load_defaults();
+
+//can user alter quickmail config?
+if (!$quickmail->check_permission('block/quickmail:canconfig', CONTEXT_COURSE, $course)) {
+    error(get_string('no_permission', 'block_quickmail'));
+}
+
+$form = new config_form();
+
+if ($form->is_cancelled()) {
+    redirect("$CFG->wwwroot/course/view.php?id=$course->id");
+}
+
+if ($data = $form->get_data()) {
+    $config = new stdClass;
+    $roleselection = array();
+
+    foreach ($data as $key => $value) {
+        $keyarr = explode(':', $key);
+        if ($keyarr[0] == ROLE_SELECT) {
+            $role = get_record('role', 'shortname', $keyarr[1]);
+            $roleselection[$role->shortname] = $role->name;
+        }
+    }
+
+    $config->allowstudents = $data->allowstudents;
+    $config->roleselection = $roleselection;
+    $config->groupmode = $course->groupmode;
+   
+    //Save into the instance without having to create a special table in the database or anything (using moodle's tables)
+    $quickmail->instance_config_save($config, $pinned);
+
+    //Redirect back to course
+    redirect("$CFG->wwwroot/course/view.php?id=$course->id");
+
+} else if (!$form->is_submitted()) {
+    //Load the form with the correct values
+
+   $form_data = array(
+        STUDENT_SELECT => $quickmail->config->allowstudents,
+        COURSE_ID => $course->id,
+        INSTANCE_ID => $quickmail->instance->id
+    );
+   
+   $quickmail_roles = $quickmail->grab_roles();
+   foreach ($quickmail_roles as $role_shortname => $role_name) {
+       $form_data[ROLE_SELECT.':'.$role_shortname] = true;
+   }    
+
+   $form->set_data($form_data);
+}
+
+$strquickmail = get_string('blockname', 'block_quickmail');
+
+$navigation = array(
+    array('name' => $course->shortname, 'link'=>"$CFG->wwwroot/course/view.php?id=$course->id", 'type'=>'title'),
+    array('name' => $strquickmail, 'link'=>'', 'type'=>'title')
+    );
+
+print_header_simple($strquickmail, '', build_navigation($navigation));
+
+print_heading('Configuring a '. $strquickmail .' block');
+$form->display();
+print_footer();
+
+?>
Index: plugins/blocks/quickmail/attachment.js
===================================================================
RCS file: plugins/blocks/quickmail/attachment.js
diff -N plugins/blocks/quickmail/attachment.js
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ plugins/blocks/quickmail/attachment.js	1 Jan 1970 00:00:00 -0000
@@ -0,0 +1,85 @@
+/*
+    Author: Philip Cali
+    Date: 2/15/2008
+    Louisiana State University
+
+    java script for applying multiple attachments
+*/
+
+//place holder for all attachment input tags
+var attachArray = new Array("attach_1");
+
+//function adds a remove link, and builds a new attachment field
+function create_new_attachment(input_id) {
+    //main table is the display table
+    main_table = document.getElementById("maintable");
+
+    //loaded attachment: an attachment field that has been loaded
+    input_tag = document.getElementById(input_id);
+    //table row associated with attachment
+    table_row = document.getElementById(input_id+"row");
+
+    var new_cell = table_row.insertCell(table_row.cells.length);
+    //create the remove link
+    new_cell.innerHTML = "<a onclick=\"remove_attachment('"+ input_id +"')\" href=\"javascript:void\">Remove</a>";
+
+    //time to create the new attachment field
+    var new_row = main_table.insertRow(main_table.findRow("attach") +1 );
+    var new_id = input_id.split("_");
+
+    var id_number = parseInt(new_id[1]) + 1;
+    new_row.id = new_id[0] + "_" + id_number + "row";
+
+    new_row.insertCell(0);
+    var input_cell = new_row.insertCell(1);
+    input_cell.colSpan = "2";
+
+    var new_input_id = new_id[0] + "_" + id_number;
+    input_cell.innerHTML = "<input id=\""+ new_input_id+ "\" name=\""+new_input_id+"\" type=\"file\" size=\"45\" onchange=\"javascript:create_new_attachment('"+ new_input_id +"')\"/>";
+    
+    //keep track of our attachments
+    attachArray.push(new_input_id); 
+    
+    //store in hidden field to process in email.php
+    document.getElementById("attachids").value=attachArray.toString();
+}
+
+//this is executed when the remove link is clicked
+function remove_attachment(input_id) {
+   //get the main display table
+   main_table = document.getElementById("maintable");
+   
+   //get table row associated with the remove link
+   table_row = document.getElementById(input_id + "row");
+    
+   //remove it
+   main_table.deleteRow(table_row.rowIndex);
+
+   //keep track
+   attachArray.remove(input_id);
+   
+   document.getElementById("attachids").value = attachArray.toString();
+}
+
+
+/** Function added to the table class that returns the index 
+ * matching the id of the row in question
+ */
+HTMLTableElement.prototype.findRow = function(id) {
+    for (i=this.rows.length-1; i>=0; i--) {
+        rowid = this.rows[i].id;
+        
+        if (rowid && id.search(rowid)) {
+            return i;
+        }
+    }
+    return -1;
+}
+
+//loaded prototype for array index removal
+Array.prototype.remove = function(s) {
+    for (i=0;i<this.length;i++) {
+        if (s==this[i]) this.splice(i, 1);
+    }
+}
+
Index: plugins/blocks/quickmail/readme.txt
===================================================================
RCS file: plugins/blocks/quickmail/readme.txt
diff -N plugins/blocks/quickmail/readme.txt
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ plugins/blocks/quickmail/readme.txt	1 Jan 1970 00:00:00 -0000
@@ -0,0 +1,73 @@
+Quickmail v2.0.3 (designed for larger classes) README
+Document created by Wen Hao Chuang (Email: enwen@sfsu.edu)
+Updated on September 18, 2007
+
+This version of quickmail is mostly based on Michael Penny and Mark Nielsen's previous work - quickmail.
+It has been tested on Moodle 1.5.x, 1.6.x, 1.7.x, and 1.8.x. All versions should work fine.
+Please file your bug report directly to enwen@sfsu.edu. Thanks!
+
+Please note, similar to the original quickmail, this block DOES require Javascript be ENABLED in your Web browser. Please check with your Web browser setting (in FireFox, go to Tools -> Options -> Content -> Enable JavaScript) to make sure this block would work correctly. Thanks! 
+
+[Why this block?]:
+   "The problem that we found here at San Francisco State University (SFSU) is
+    that some of our faculty members have classes that have more than 100+
+    students. The original quickmail Graphics User Interface (GUI) does not
+    really fit with their needs. We hacked the GUI a little bit so that it
+    becomes more user-friendly for larger classes."
+
+Here are a list of files that were modified from the original quickmail block:
+
+Added: selection.js (a javascript file that defines functions used by email.html) and /lang/help
+Modified: email.html, email.php, config_instance.html, block_quickmail.php (minor modification)
+Same: styles.php, \db\, and most part of \lang folder
+
+Added/Removed features:
+=======================
+1. We removed the "Email history" feature but added a feature that instructors could use their
+   external email client (e.g. Outlook, Eudora, thunderbird) for quickmail. The email receipients will be
+   included in the BCC field, and the instructor's email will be in the To field. As we have many
+   quickmail users we don't want to use our precious server space to keep all these logs (it can
+   really add up if users use it very often with attachments, etc.)
+2. We added a HELP button for this block, to enhance usability. This was based on our instructors'
+   request as they were not quite sure what quickmail could do for them. We also added a help
+   button to explain how they could use external email client to keep track of their quickmail
+   history
+3. We temporarily removed the "Group mode" settings, although the codes are still included in
+   this release. You just have to remove the comments of the codes to enable this feature.
+   However, we haven't been tested the Group mode in Moodle 1.8 yet. (Group codes are still not
+   very stable in Moodle 1.8 yet).
+
+How to install:
+===============
+1. Unzip the quickmailv2.zip into your moodle "blocks" folder, create a folder called quickmail
+   and put all your files in that folder
+2. Move the block_quickmail.php included in \lang\en to your language folder (e.g. \lang\en_utf8).
+   If you are using other languages you probably need a language package for proper translation.
+   By the way, you might have some luck to get one from the previous quickmail v1. See:
+   http://moodle.org/mod/data/view.php?d=13&rid=92
+3. Put the \lang\en\help\*.html into the \lang\en\help (or \lang\en_utf8\help for Moodle 1.6 or above) 
+   in your moodle installation.
+   These are the help button content of the quickmail block.
+   You could modify the content based on your needs.
+
+How to uninstall:
+=================
+1. Simply remove the block\quickmail folder and related quickmail database tables and that's it!
+
+Notes:
+======
+1. Currently we disabled the group feature, as this is still under testing now. If you are interested to help out with testing or rewriting, please contact with me (Wen).
+2. There are two files that has identical filename: block_quickmail.php. One should be put under\lang\en, the other under \blocks\quickmail. These two files should not be confused.
+3. Unless you know how to tweak the codes, otherwise we don't recommend installing two versions of quickmails on the same moodle installation.
+4. You could remove the 
+5. If you created a language pack that you would like me to include for the next release please send me the files, thanks!
+6. The implementation of the database part (table) is exactly the same with previous Quickmail v1.
+7. If you would like to have different view for the list of "Potential Recipient(s)," you could
+   hack around line#88 in email.html code. Thanks for Art Lader contribute this quick question.
+
+We hope that you will enjoy using this block. Thanks!
+
+The newest version could be downloaded from:
+http://moodle.org/mod/data/view.php?d=13&rid=764
+
+Wen
